简体   繁体   English

使用awk编辑文件内的字段

[英]Edit fields inside a file using awk

I am trying to modify the second field of a list of data using awk 我正在尝试使用awk修改数据列表的第二个字段

Input : 输入:

8 : /usr/local/lib/python2.7/test/test_cookie.py : Image

Output: 输出:

8 : /usr/local/lib/python2.7/test/ : Image

I wanted to remove the file name from the second field using awk or sed. 我想使用awk或sed从第二个字段中删除文件名。

I already tried using awk command inside another awk to replace the second field of the input file. 我已经尝试在另一个awk中使用awk命令来替换输入文件的第二个字段。 However this is giving me error : 但是,这给了我错误:

cat log.txt |awk -F: '{$2=system(cat log.txt |awk -F":" '{print $2}'|awk -F/ '{OFS="/";$NF=""}{print $0}' )}{print $0}'

Can you help me with a more probable way to do the same. 您能以一种更可能的方式帮助我吗?

You can use this awk : 您可以使用以下awk

awk 'BEGIN{FS=OFS=" : "} {sub(/[^\/]+$/, "", $2)} 1' log.txt
8 : /usr/local/lib/python2.7/test/ : Image

Explanation: 说明:

BEGIN{FS=OFS=" : "}      # Set input and output field separator as " : "
sub(/[^\/]+$/, "", $2)   # Remove part after *last* / from 2nd field
1                        # default awk action to print the record

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM