Anurag Sharma
Anurag Sharma

Reputation: 5039

awk to modify content of file

I have a file which is tab '\t' separated like this

8   263 722016-8-263-2016_02_07_03:00:18-544992 Text1   4
8       722016-8--2016_02_07_03:00:18-307392    Text2   1
8   220 722016-8-220-2016_02_07_03:00:18-488656 Text3   3
8   727 722016-8-727-2016_02_07_03:00:18-786195 Text4   1

I have to modify the content of 3rd column. I can get the 3rd column like this awk '{ print $3 }' file.txt.

722016-8-263-2016_02_07_03:00:18-544992
Text2
722016-8-220-2016_02_07_03:00:18-488656 
722016-8-727-2016_02_07_03:00:18-786195

But in line 2 column 2 is missing, I am getting Text2 in the output instead of 722016-8--2016_02_07_03:00:18-307392. so I am thinking getting 3rd column from the last and inserting "Test1-" at the start of that column. Expected output for the above file will be --

8   263 Test1-722016-8-263-2016_02_07_03:00:18-544992   Text1   4
8       Test1-722016-8--2016_02_07_03:00:18-307392      Text2   1
8   220 Test1-722016-8-220-2016_02_07_03:00:18-488656   Text3   3
8   727 Test1-722016-8-727-2016_02_07_03:00:18-786195   Text4   1

Upvotes: 1

Views: 49

Answers (1)

anubhava
anubhava

Reputation: 785156

You can use this awk:

awk 'BEGIN{FS=OFS="\t"} NF==4{$1=$1 "\t"} {$(NF-2) = "Test1-" $(NF-2)} 1' file

Output:

8   263 Test1-722016-8-263-2016_02_07_03:00:18-544992   Text1   4
8       Test1-722016-8--2016_02_07_03:00:18-307392      Text2   1
8   220 Test1-722016-8-220-2016_02_07_03:00:18-488656   Text3   3
8   727 Test1-722016-8-727-2016_02_07_03:00:18-786195   Text4   1

Upvotes: 2

Related Questions