Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk: find and replace in certain field only [closed]

Tags:

linux

bash

awk

I have a text file like this:

$ cat test
12 13 2100 s
12 13 3100 s
100 13 100 s
12 13 300 s

I want the output to be like this:

$ cat test
12 13 22000 s
12 13 32000 s
100 13 2000 s
12 13 300 s

I only want to replace 100 in field 3 (once 100 is contained in $3) into 2000. How can I accomplish this job using awk?

like image 333
Yishu Fang Avatar asked Dec 08 '22 18:12

Yishu Fang


2 Answers

Here's one way using awk:

awk '{ sub(/100$/, "2000", $3) }1' file

Results:

12 13 22000 s
12 13 32000 s
100 13 2000 s
12 13 300 s
like image 56
Steve Avatar answered Dec 11 '22 08:12

Steve


Try:

awk '{$3=gensub(100,2000,1,$3);print}' test.txt
like image 43
anishsane Avatar answered Dec 11 '22 09:12

anishsane