【问题标题】:Replace column after performing actions using awk使用 awk 执行操作后替换列
【发布时间】:2018-06-08 11:54:32
【问题描述】:

在下面,我试图仅从 msg 列中删除逗号。

输入文件("abc.txt"有很多条目如下):

alert tcp any any -> any [10,112,34] (msg:"Its an Test, Rule"; reference:url,view/Main; sid:1234; rev:1;)

预期输出:

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

【问题讨论】:

  • 试试 (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 '}'
  • @ghoti 感谢告知,到目前为止,我从未使用过非 GNU sed。
  • @mahi,你从来没有选择一个答案作为正确答案,所以请花点时间在这里检查用户的所有答案,然后选择其中任何一个作为正确答案,这有助于你正确关闭线程,干杯.
  • 或者简单地用 sed: sed ':A;s/(msg:"[^,"]*),/\1/;tA'

标签: shell awk gsub


【解决方案1】:

让 awk 重写字段的问题是修改后的行的输出将由 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.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多