shell - BASH : Find number in text -> variable

标签 shell sed awk grep

我几乎不需要社区的帮助:

我在一个大文本文件中有这两行:

Connected clients: 42  
4 ACTIVE CLIENTS IN LAST 20 SECONDS  

如何查找、提取数字并将其分配给变量?
clients=42
active=4

SED、AWK、GREP?我应该使用哪一种?

最佳答案

clients=$(grep -Po '^(?<=Connected clients: )([0-9]+)$' filename)
active=$(grep -Po '^([0-9]+)(?= ACTIVE CLIENTS IN LAST [0-9]+ SECONDS$)' filename)

或者
clients=$(sed -n 's/^Connected clients: \([0-9]\+\)$/\1/p' filename)
active=$(sed -n 's/^\([0-9]\+\) ACTIVE CLIENTS IN LAST [0-9]\+ SECONDS$/\1/p' filename)

关于shell - BASH : Find number in text -> variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4729683/

相关文章:

regex - 如何在/bin/sh脚本中编写并匹配正则表达式?

bash - 在 bash 上逐行读取文件;每行包含另一个独特文件的路径

regex - 将 bash 正则表达式模式作为 awk 中更大的正则表达式模式的一部分传递

查找二元组的 Shell 脚本

regex - 如何使用 sed 在文件中创建此模式

bash - bash中除第一个单词外的字符串的相反顺序

unix - 尝试使用 'sed -i' 修改文件时出错

shell - 递归重命名文件 Mac OSX

linux - 根据列的值保留唯一 ID?

bash - 使用 exiftool 中的 GPS 位置在 Bash 中进行反向地理编码