I am trying to change the city on all records and keep the header.
What I have:
Name,City,State Bob,Portland,Oregon Sue,Portland,Oregon David,Portland,Oregon What I want:
Name,City,State Bob,Bend,Oregon Sue,Bend,Oregon David,Bend,Oregon What I have tried:
awk -F',' 'NR>1 $2 == "Portland" {$2 = "Bend";print}' OFS="," Any help will be greatly appreciated
1 Answer
Try:
$ awk -F',' 'NR>1 && $2 == "Portland" {$2 = "Bend"} {print}' OFS="," file Name,City,State Bob,Bend,Oregon Sue,Bend,Oregon David,Bend,Oregon or, using the usual awk shorthand:
awk -F',' 'NR>1 && $2 == "Portland" {$2 = "Bend"} 1' OFS="," file Notes:
When you have two conditions, like
NR>1and$2 == "Portland"and your want both to apply, they need to be combined with logical-and:&&.You want all lines printed and awk does not print by default. So, we moved the print command to a separate group so it applied to all lines.
Alternative: using sed
Using sed, we can get the same result:
$ sed 's/,Portland,/,Bend,/' file Name,City,State Bob,Bend,Oregon Sue,Bend,Oregon David,Bend,Oregon 1