英文:
Replace all surnames following 'Mr' prefix using bash script
问题
我有一个CSV文件,每一行都包含一个人的名字,格式如下:
| 11th October | 06 6606 1161 | Mr Bean is 43 years old. Mr Bean likes apples. |
我的目标是编写一个Bash脚本,将文件中的姓氏替换为新姓氏。
例如,使用一个名为replace_surname.sh
的脚本:
#!/bin/sh
if [ ! -z $1 ]
then
# 在'Mr'后面替换姓氏为$1
fi
给定上述的CSV文件和命令replace_surname.sh Smith
,我期望得到以下结果:
| 11th October | 06 6606 1161 | Mr Smith is 43 years old. Mr Smith likes apples. |
我尝试过以下方法:
sed -i 's/^Mr .*$/Mr PacMan/' test.csv
以及一些其他方法,来自这里,但都没有对文件产生影响。
我有点困惑,我的CSV文件有数百条记录,所以不想手工处理!非常感谢任何帮助
英文:
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
答案1
得分: 1
这应该可以:
#!/bin/sh
if [ -n "$1" ]; then
new_surname="$1"
sed -i "s/Mr\s\+\(\w\+\)/Mr ${new_surname}/g" /tmp/mr
fi
这是如果旧姓只有一个单词的情况下。
正则表达式可以进一步改进,但你应该能明白这个思路。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论