[英]Awk/sed command to print pattern1 only if patterm 2 macthes
Trying to get the "Log" line printed only if "ref1" is present in the text following the "Log" line仅当“日志”行后面的文本中存在“ref1”时才尝试打印“日志”行
sample text:示例文本:
Log 0102
............
.....ref1.......
......ref1....
Log 0103
............
.....ref1.......
....
Log 0104
............
.....ref2.......
......
expected result:预期结果:
Log 0102
Log 0103
result i am getting:结果我得到:
Log 0102
Log 0102
Log 0103
i tried this awk command but not getting results:我试过这个 awk 命令但没有得到结果:
awk '/Log*/ line =$0}/ref1/{print line}'
With your shown samples please try following awk
code.对于您展示的样品,请尝试遵循awk
代码。
awk '
/^Log/{
if(found){ print value }
value=$0
found=""
next
}
/ref1/{
found=1
}
END{
if(found){
print value
}
}
' Input_file
OR a one-liner form of above code.或上述代码的单行形式。
awk awk '/^Log/{if(found){print value};value=$0;found="";next} /ref1/{found=1} END{if(found){print value}}' Input_file
Using gnu-awk
this is fairly simple with custom RS
:使用gnu-awk
使用自定义RS
相当简单:
awk -v RS='(^|\n)Log ' '/ref1/ {printf "Log %s\n", $1}' file
Log 0102
Log 0103
Here -v RS='(^|\n)Log '
sets RS
to Log
followed by a space.这里-v RS='(^|\n)Log '
将RS
设置为Log
后跟一个空格。 Log
should be preceded by start position or a line break. Log
前面应该有 start position 或换行符。
mawk 'gsub("^|Log [^\n]+|"FS,"\1&\2",$,(NF-=+_<NF)) + \ gsub("\2[^\1\2]*\1","\n") + \ gsub("^[\1\2]+|[\1\2]\n[^\1\2]+$",_)^_' RS= FS='ref1'
Log 0102
Log 0103
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.