1

I’m using bash and wondering if there is a way to do a search and replace with given conditions. I have a CSV file with rows resembling the following …

Ira,Frances,Lancaster,373611,06211101,239661,239661,8,8/16/01

If the 6th and 7th columns contain the same values, I would like to replace the 7th column with an empty string, so the above would become

Ira,Frances,Lancaster,373611,06211101,239661,,8,8/16/01

I’m using Mac 10.9.5 with bash shell. What is the shortest way to edit the file to remove the data I want?

2 Answers 2

1

You can use awk for this:

awk -F, -v OFS=, '$6 == $7 {$7=""} 1' file.csv

Testing:

s='Ira,Frances,Lancaster,373611,06211101,239661,239661,8,8/16/01'
awk -F, -v OFS=, '$6 == $7 {$7=""} 1' <<< "$s"
Ira,Frances,Lancaster,373611,06211101,239661,,8,8/16/01
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This command seems to work but it removes all the commas from my file. Anywya I can preserve the commas and just remove the values I dont want?
I just updated to preserve comma and provided a test code as well.
0

Awk solution :

awk -F,'{if  ($6 ==  $7) {$7 =""; print $0} }' file.csv

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.