bash 如何在 a 是变量赋值的行中对子字符串进行 GREP?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9744845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to GREP a substring in a line which a is variable assignment?
提问by Lev Levitsky
I have an output which is of the format
我有一个格式的输出
OK: CpuUser=0.11; CpuNice=0.00; CpuSystem=0.12; CpuIowait=0.02; CpuSteal=0.00;
确定:CpuUser=0.11;CpuNice=0.00;中央处理器=0.12;CPUIowait=0.02;CpuSteal=0.00;
I want to get just the CpuIowait=0.12 as output. I want to grep just a specific substring. How do I do that?
我只想得到 CpuIowait=0.12 作为输出。我只想 grep 一个特定的子字符串。我怎么做?
回答by ruakh
You can use the -o
("only") flag. This command:
您可以使用-o
("only") 标志。这个命令:
grep -o 'CpuIowait=[^;]*'
will print out the specific substrings that match CpuIowait=[^;]*
, instead of printing out the whole lines that contain them.
将打印出匹配的特定子字符串CpuIowait=[^;]*
,而不是打印出包含它们的整行。
回答by Lev Levitsky
If you want to use grep
, try something like this:
如果要使用grep
,请尝试以下操作:
echo "OK: CpuUser=0.11; CpuNice=0.00; CpuSystem=0.12; CpuIowait=0.02; CpuSteal=0.00;" | grep -oE "CpuIowait=[[:digit:]]*\.[[:digit:]]*"
回答by xtopher
If you're not dead set on using grep
, you can pipe the input to sed
:
如果您不是死心塌地使用grep
,则可以将输入通过管道传输到sed
:
sed -ne "s/^.*\(CpuSystem=[0-9.]*\);.*$//p;"
From man sed
:
来自man sed
:
-n, --quiet, --silent
: suppress automatic printing of pattern space
-e script, --expression=script
: add the script to the commands to be executed
-n, --quiet, --silent
: 抑制模式空间的自动打印
-e script, --expression=script
: 将脚本添加到要执行的命令中
回答by jordanm
To get the entire string:
要获取整个字符串:
var=$(grep -Eo 'CpuIowait=[0-9]{1,2}[.][0-9]{2}' < <(command))
To get just the value, if you have GNU grep with -P, you can use the following:
要获得该值,如果您有带 -P 的 GNU grep,则可以使用以下命令:
var=$(grep -Po '(?<=CpuIowait=).*(?=;)' < <(command))
Using awk:
使用 awk:
var=$(awk -F'; |: ' '{ for (i=0;i<=NF;i++) { split($i,arr,/=/); if (arr[1] == "CpuIowait") { print arr[2] } } }' < <(command))
Using pure bash:
使用纯 bash:
output=$(command)
[[ $output =~ (CpuIowait=[0-9][.][0-9]{2}) ]] && echo "${BASH_REMATCH[1]}"