linux 如何使用awk进行多字符定界符?

2exbekwf  于 2022-12-11  发布在  Linux
关注(0)|答案(4)|浏览(117)

我有一个日志文件,其中包含如下行:

Insert request received from system 1
Modify request received from system 2

我想从日志中获取“received from”后面的文本。等效的grep和cut命令将是(如果它支持多字符分隔符)

grep "received from" mylogfile.log | cut -d"received from" -f1

如何使用awk重新创建

dxxyhpgq

dxxyhpgq1#

FS可以是字符串或awk中的正则表达式。

awk -F' received from ' 'NF > 1 {print $2}' mylogfile.log

您还可以使用sed删除received from之前的所有内容:

sed -n 's/.*received from //p' mylogfile.log
jm2pwxwz

jm2pwxwz2#

您可以按照以下方式执行此操作,让file.txt内容为

Insert request received from system 1
Modify request received from system 2

然后

awk 'sub(/.*received from /,"")' file.txt

给出输出

system 1
system 2

说明:我使用带有2个参数的sub string function:正则表达式和空字符串,因此它会就地更改当前行,如果进行了更改,则返回1,否则返回0,然后将此值用于选择-仅打印进行了更改的行。警告:该解决方案假设每行最多具有1 × 1 M2 N1 X,如果这不成立,则将最右边的一个视为定界符。

  • (在GNU Awk 5.0.1中测试)*
ssgvzors

ssgvzors3#

您可以将字段分隔符设置为received from,然后打印第二个字段(如果存在):

awk -F' received from ' 'NF > 1 {print $2}' mylogfile.log

或者使用split并检查是否存在第二个字段:

awk '{
  n = split($0,a," received from ")
  if (n > 1) print a[2]
}' mylogfile.log

输出量

system 1
system 2

相关问题