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 –
#!/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