Shasha99 Shasha99 - 7 months ago 7
Bash Question

Updating value under specified column in the file using shell

I have a text file in the following format:

# this is the comment
# And this is also a comment

FIELD1
COL11 COL12 COL13
5 10 15

FIELD2
COL21 COL22 COL23 COL24
12 34 45 55

.......
.......


I want to update the value mentioned under COL24 (55) to some other value lets say 100.I can read that value using the following shell:

grep -A 1 COL21 /Dir/To/File/filename.txt | sed -e '1 d' | awk -F ' ' '{print $4}


But how do we update the value ?

Answer

You can use this awk command:

awk '/FIELD2/{r=NR} r && NR==r+2{$4=100} 1' OFS='\t' file