如何编辑定义位置的awk输出行



有办法解决这个问题吗?

我有一个bash脚本,它从源文件创建.dat和.log文件。我正在使用awk打印和定位我需要打印的内容。问题出在最后一个位置-ID2(下(。它应该只是*[0-9]{3}*#,但在某些情况下,[0-9]{12}[00]>之前有一个字符串。然后一行看起来像这样:

2020-01-11 01:01:01;test;test123;123456789123[00]>*123*#

我需要的是在文件中删除之前的字符串:

2020-01-11 01:01:01;test;test123;*123*#

文件结构:

YYYY-DD-MM HH:MM:SS;string;ID1;ID2

我很乐意接受任何建议,谢谢。

awk 'BEGIN{FS=OFS=";"} {$NF=substr($NF,length($NF)-5)}1' file

这里我们只保留最后一个字段的最后6个字符,而分号是字段分隔符。如果*ID*#前面没有其他内容,那么我们保留所有内容。

删除第一个*:之前的所有内容

$ awk 'BEGIN{FS=OFS=";"}{sub(/^[^*]*/,"",$NF)}1' file

输出:

2020-01-11 01:01:01;test;test123;*123*#

你能试着用GNUawk中显示的示例测试和编写以下内容吗。

awk '
match($0,/[0-9]{12}[[0-9]+]>/) && /*[0-9]{3}*#/{
print substr($0,1,RSTART-1) substr($0,RSTART+RLENGTH)
}
'  Input_file

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

awk '                                                        ##Starting awk program from here.
match($0,/[0-9]{12}[[0-9]+]>/) && /*[0-9]{3}*#/{         ##Using match function to match regex in it, what regex does is: It matches digits(12 in number) then [ then digits(continuously coming) and ] Also checking condition if line ends with *3 digits *
print substr($0,1,RSTART-1) substr($0,RSTART+RLENGTH)      ##If above condition is TRUE then printing sub-string from 1st character to RSTART-1 and then sub-string from RSTART+RLENGTH value to till last of line.
}
'  Input_file                                                ##Mentioning Input_file name here.

最新更新