简体   繁体   中英

Running search and replace for only certain values using bash shell

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?

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

AWK解决方案:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM