Prashanth
Prashanth

Reputation: 7

Replace a field with a value in the input data

I have a data

A BC 3 CD

note that the spaces in between the fields are not constant

Now I want to replace the third field with another number which is stored in another variable v. I have used awk in this way:

echo "A     BC      3       CD" | awk '{$3 = $v; print}' 

The output is the third field is getting replaced with the entire line(wrong output) Is there any possible to get the desired output without changing the spaces in the original data? Thanks for your help!!

Upvotes: 0

Views: 72

Answers (1)

anishsane
anishsane

Reputation: 20980

Try this:

$ v=25
$ echo "A     BC      3       CD" | gawk '{print gensub(/[^ \t]+/, v, 3)}' v="$v"
A     BC      25       CD

In your code, $v is being evaluated by awk, not bash, with v=0. Hence $3 gets replaced by $0, which is entire line.

Note that gensub is gawk enhancement...

Upvotes: 1

Related Questions