Atul
Atul

Reputation: 1

Replace whatever comes in specific field with awk

Suppose I have data like

name,age

sam,20

pam,30

I want to replace whatever comes in field 2 (i.e 20 and 30) with a given value stored in a variable var=10. I specifically dont want to do the same for first line.

desired o/p

name,age

sam,10

pam,10

Upvotes: 0

Views: 64

Answers (2)

Kent
Kent

Reputation: 195209

awk -F, -v OFS="," -v n="10" 'NR>1&&NF==2{$2=n}7' file

test:

kent$ (US-6966|✔) echo "name,age

sam,20

pam,30"|awk -F, -v OFS="," -v n="10" 'NR>1&&NF==2{$2=n}7'
name,age

sam,10

pam,10

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174796

Try this awk command to replace the value in column two with the value stored in a variable(ie, 10),

$ awk -F, -v var=10 'NR==1{print; next} /^ *$/{next}{gsub(/.*/,var,$2)}1' OFS="," file
name,age
sam,10
pam,10

OR

if you want to print the blank lines also then try this command,

$ awk -F, -v var=10 'NR==1{print; next} /^ *$/{print; next}{gsub(/.*/,var,$2)}1' OFS="," file
name,age

sam,10

pam,10

Upvotes: 1

Related Questions