使用Bash脚本替换所有跟在’Mr’前缀后面的姓氏。

huangapple go评论83阅读模式
英文:

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文件有数百条记录,所以不想手工处理!非常感谢任何帮助 使用Bash脚本替换所有跟在’Mr’前缀后面的姓氏。

英文:

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 使用Bash脚本替换所有跟在’Mr’前缀后面的姓氏。

答案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

huangapple
  • 本文由 发表于 2023年7月23日 17:16:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定