在模式之间查找并在模式之间处理



我有一个如下的文件格式,

####################### FILE Content ###################
Path 1
AND cell
OR1 cell
BUFF1 cell
OR2 cell
Ends
Path 2
OR1 cell
BUFF1 cell
AND1 cell
AND2 cell
BUFF2 cell
OR2 cell
Ends
Path 3
AND1 cell
AND2 cell
AND3 cell
OR1 cell
Ends
##########################################

我需要如下输出:

Path 1 - BUFF* count 1
Path 2 - BUFF* count 2
Path 3 - No BUFF

通过使用sed,我可以首先获得Pattern to Pattern like。sed -n '/Path/,/Ends/p'为了在那之后获得Ouput,我需要你的专业知识帮助。有人能帮帮我吗。

感谢GB

您可以使用awk并使用模式来检查您是否位于数字后面的Path和Ends之间。

当它与Ends匹配时,打印您所在的当前路径和BUFF的计数。

然后重置看到的变量并进行buff。

awk '
/^Path [0-9]+/{seen=1; buff=0; path=$0; next}
{
if(seen && $1 ~ /^BUFF[0-9]+$/){++buff;}
}
{
if(seen && $1 ~ /^Ends$/){
print path " - " (buff ? "BUFF* count " buff : "No BUFF")
seen=0; buff=0    
}
}
' file

输出

Path 1 - BUFF* count 1
Path 2 - BUFF* count 2
Path 3 - No BUFF

使用显示的示例,尝试;请在awk中尝试以下代码。

awk '
/Path/{
if(count){
print pathVal," - BUFF* count "(count?count:"NO BUFF")
}
found=""
count=0
pathVal=$0
next
}
/BUFF/{
count++
}
/Ends/{
found=1
}
END{
if(found){
print pathVal," - BUFF* count "(count?count:"NO BUFF")
}
}
'  Input_file

解释:添加以上详细解释。

awk '             ##Starting awk program from here.
/Path/{           ##If line contains Path then do following.
if(count){      ##If count is set then do following.
print pathVal," - BUFF* count "(count?count:"NO BUFF") ##Printing output with variables and string as per OP need here.
}
found=""        ##Nullifying found here.
count=0         ##Setting 0 to count here.
pathVal=$0      ##Setting current line to pathVal here.
next            ##next will skip all further statements from here.
}
/BUFF/{           ##Checking if BUFF is found in line then increase count with 1 here.
count++
}
/Ends/{           ##Checking if Line contains Ens then setting found to 1 here.
found=1
}
END{              ##Starting END block of this program from here.
if(found){      ##If found is set then print as per OP requirement values with strings.
print pathVal," - BUFF* count "(count?count:"NO BUFF")
}
}
'  Input_file     ##Mentioning Input_file name here. 

这可能适用于您(GNU sed&shell(:

sed -n '/^Path.*/{s//& - BUFF* count $((0))/;h}
/^BUFF/{g;s/(0/(0+1/;h}
/^Ends/{g;/+/!s/-.*/- No BUFF/;s/^Path.*/echo "&"/ep;z;h}' file

对于每个Path,制作一个副本,添加一些文本并初始化一个计数器。

对于每个BUFF,递增计数器。

对于每个Ends,如果计数器尚未递增,则用不同的文本替换添加的文本。将整个消息用双引号括起来,并通过评估结果来回显结果,然后进行清理。

注意:计数器将插入回显命令的双引号内。

awk处于段落模式,并使用gsub()函数获取/BUFF[[:digit:]]+/出现的次数:

awk -v RS= -v FS='n' '
$1 ~ /Path/ && $NF == "Ends"  && /BUFF/{
n=gsub(/BUFF[[:digit:]]+/,"&");print $1 " - BUFF* count " n}
$1 ~ /Path/ && $NF == "Ends"  && !/BUFF/{
print $1 " - No BUFF"}
' file
Path 1 - BUFF* count 1
Path 2 - BUFF* count 2
Path 3 - No BUFF

相关内容

  • 没有找到相关文章

最新更新