Shell 使用awk执行操作后替换列
下面我试图从msg列中删除逗号 输入文件(“abc.txt”有许多条目,如下所示): 预期产出:Shell 使用awk执行操作后替换列,shell,awk,gsub,Shell,Awk,Gsub,下面我试图从msg列中删除逗号 输入文件(“abc.txt”有许多条目,如下所示): 预期产出: alert tcp any any -> any [10,112,34] (msg:"Its an Test Rule"; reference:url,view/Main; sid:1234; rev:1;) 这就是我使用awk所尝试的: awk -F ';' '{for(i=1;i<=NF;i++){if(match($i,"msg:")>0){split($i, array,
alert tcp any any -> any [10,112,34] (msg:"Its an Test Rule"; reference:url,view/Main; sid:1234; rev:1;)
这就是我使用awk所尝试的:
awk -F ';' '{for(i=1;i<=NF;i++){if(match($i,"msg:")>0){split($i, array, "\"");tmessage=array[2];gsub("[',']","",tmessage);message=tmessage; }}print message'} abc.txt
awk-F';“”{for(i=1;i0){split($i,array,“\”);tmessage=array[2];gsub(“[”,“]”,“,”,tmessage);message=tmessage;}}}}print message'}abc.txt
让awk重写字段的问题是,修改行的输出将由OFS分隔,OFS是静态的
解决方法是避免处理字段,只需在$0
上处理字符串替换。您可以手动将行的各个部分拼凑在一起,如下所示:
awk '{x=index($0,"msg:"); y=index(substr($0,x),";"); s=substr($0,x,y); gsub(/,/,"",s); print substr($0,1,x-1) s substr($0,x+y)}' input.txt
或为便于阅读而拼写:
{
x=index($0,"msg:") # find the offset of the interesting bit
y=index(substr($0,x),";") # find the length of that bit
s=substr($0,x,y) # clip the bit
gsub(/,/,"",s) # replace commas,
print substr($0,1,x-1) s substr($0,x+y) # print the result.
}
尝试使用(GNU)sed
:sed'/(msg:“/{:a s/\((msg:“[^”,]*\),/\1/;t a}'
@WiktorStribiżew-如果将一些片段分开,则此逻辑在非GNU sed中也有效:sed-e'/(msg:“/{:a'-e's/\((msg:“[^”,]*\),/\1/\t a'-e'-e'}“
@ghoti谢谢你让我知道,到目前为止我从未使用过非GNU sed。@mahi,你从来没有选择过一个答案作为正确答案,因此请花点时间检查这里用户的所有答案,然后选择其中任何一个作为正确答案,这有助于你正确关闭线程,干杯。或者简单地使用sed:sed::a;s/(msg:[^,]*),/\1/;tA”
{
x=index($0,"msg:") # find the offset of the interesting bit
y=index(substr($0,x),";") # find the length of that bit
s=substr($0,x,y) # clip the bit
gsub(/,/,"",s) # replace commas,
print substr($0,1,x-1) s substr($0,x+y) # print the result.
}