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:

  1. When you have two conditions, like NR>1 and $2 == "Portland" and your want both to apply, they need to be combined with logical-and: &&.

  2. 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy