请一些帮助... 我的Linux机器上的文件中有一个文本块,就像这样;
Block.1:\
:Value1=something:\
:Value2=something_else:\
:Value3=something_other:
Block.2:\
:Value1=something:\
:Value2=something_else:\
:Value3=something_other:
Block.n:\
:Value1=something:\
:Value2=something_else:\
:Value3=something_other:
我如何使用grep(和/或可能是awk?)来从Block2中拔出例如Value2? 块不会总是按顺序排序(它们具有任意名称),但始终是唯一的。 冒号和反斜杠的位置是绝对的。 TIA,Rob。
答案 0 :(得分:2)
关注awk
可能对您有帮助。
awk -F"=" '/^Block\.2/{flag=1} flag && /Value2/{print $2;flag=""}' Input_file
输出如下。
something_else:\
如果您想在第2栏中打印整行value2
,请在上面的代码中从print $2
更改为print
。
说明: 现在也添加上述代码的说明。
awk -F"=" ' ##Creating field separator as = for each line of Input_file.
/Block\.2/{ ##Checking condition if a line is having string Block.2, here I have escaped . to refrain its special meaning, if condition is TRUE then do follow:
flag=1 ##Setting variable flag value as 1, which indicates that flag is TRUE.
}
flag && /Value2/{ ##Checking condition if flag value is TRUE and line is having string Value2 in it then do following:
print $2; ##Printing 2nd field of the current line.
flag="" ##Nullifying the variable flag now.
}
' Input_file ##Mentioning the Input_file name here.
答案 1 :(得分:0)
$ cat tst.awk
BEGIN { FS="[:=]" }
NF==2 { f = ($1 == "Block.2" ? 1 : 0) }
f && ($2 == "Value2") { print $3 }
$ awk -f tst.awk file
something_else
答案 2 :(得分:0)
grep -A 2 "Block.2" | tail -1 | cut -d= -f2
解释: