简体   繁体   中英

Edit fields inside a file using awk

I am trying to modify the second field of a list of data using 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.

I already tried using awk command inside another awk to replace the second field of the input file. 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 '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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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