在文件中搜索带分隔符的字符串,然后打印该字符串,直到在linux中找到下一个分隔符
我在一个文件中有下面的文本在文件中搜索带分隔符的字符串,然后打印该字符串,直到在linux中找到下一个分隔符,linux,shell,scripting,Linux,Shell,Scripting,我在一个文件中有下面的文本 1|2|SID1=/some/path|SID2=/some/path|4|5 1|2|SID1=/some/path|tel|path|SID2=/some/path|6|5|ord|til 1|2|SID1=/some/path|id1|id2|id3|SID2=/some/path|4|8|dea 在Linux中,如何搜索每行中的SID1和SID2,并只打印到下一个分隔符,这样输出应该是 SID1=/some/path SID2=/some/path SID1
1|2|SID1=/some/path|SID2=/some/path|4|5
1|2|SID1=/some/path|tel|path|SID2=/some/path|6|5|ord|til
1|2|SID1=/some/path|id1|id2|id3|SID2=/some/path|4|8|dea
在Linux中,如何搜索每行中的SID1和SID2,并只打印到下一个分隔符,这样输出应该是
SID1=/some/path SID2=/some/path
SID1=/some/path SID2=/some/path
SID1=/some/path SID2=/some/path
救援人员:
perl -lne 'print join " ", /SID[12]=[^|]*/g' file.txt
说明:Perl逐行读取文件(-n)。包含SID、1或2、后跟=和除|以外的任何内容的行的所有部分都在它们之间打印了一个空格。我觉得我缺少了一个更好的解决方案,但这是可行的 一行:
awk -F'|' '{a=0; for (i=1; i<=NF; i++) {if ($i ~ /^SID[[:digit:]]*=/) { printf "%s%s", a?OFS:(NR>1)?ORS:"", $i; a++ }}} END {print ""}' file
awk-F'|'''{a=0;for(i=1;i1)?or:,$i;a++}}END{print'}文件
解释:
awk -F'|' '{
# Reset our field tracking.
a=0
# Loop over all the fields in the line.
for (i=1; i<=NF; i++) {
# If the current field starts with 'SID#=' then
if ($i ~ /^SID[[:digit:]]*=/) {
# Print out the field with the appropriate separator.
# When we have 'a' set we are in a line and want to print out a
# leading OFS. Otherwise if this is not the first line we want to
# print out a leading ORS. Otherise do nothing.
printf "%s%s", a?OFS:(NR>1)?ORS:"", $i
# Set our field tracking.
a=1
}
}
}
END {
# Print out the final newline.
print ""
}' file
awk-F'|''{
#重置我们的现场跟踪。
a=0
#循环行中的所有字段。
对于(i=1;i1)?OR:,$i
#设置我们的现场跟踪。
a=1
}
}
}
结束{
#打印出最后的换行符。
打印“”
}"档案"
我正在尝试以下代码cat filename | awk-F“|”{for(I=1;iDefine“不工作”。看起来它应该在自己的行上打印每行的每个字段。这也会抓取像|BOO SID1=/some/path |
这样的字段,不是吗?@EtanReisner:是的。如果它们存在,并且SID可以出现在行的最开头,请使用类似于/(?:^ ^ ^ ^ \\\\.*)(SID[12]=[^ ^]]*)/g
。感谢您使用了这么多perl命令。我也将尝试awk