Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace all surnames following 'Mr' prefix using bash script

I have a csv file where each line contains a person’s name like this.

| 11th October  | 06 6606 1161 | Mr Bean is 43 years old. Mr Bean likes apples. |

My goal is to write a bash script to replace the surnames in the file with a new surname.

So for example with a script replace_surname.sh

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/bin/sh

if [ ! -z $1 ]
then
    #replace surname following 'Mr' with $1
fi

I’d expect, given the above csv and the command replace_surname.sh Smith

| 11th October  | 06 6606 1161 | Mr Smith is 43 years old. Mr Smith likes apples. |

What I’ve tried –

sed -i 's/^Mr .*$/Mr PacMan/' test.csv

And a few other from here
Which doesn’t affect the file at all.

I’m a bit stuck and my csv file has hundreds of records so I wouldn’t like to do it all by hand! Any help is very much appreciated 🙂

>Solution :

This should do it:

#!/bin/sh

if [ -n "$1" ]; then
  new_surname="$1"
  sed -i "s/Mr\s\+\(\w\+\)/Mr ${new_surname}/g" /tmp/mr
fi

that is if the old surname is 1 word

Regex can be further improved, but you should get the idea

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading