Replace one substring for another string in shell script

匿名 (未验证) 提交于 2019-12-03 02:23:02

问题:

I have "I love Suzi and Marry" and I want to change "Suzi" to "Sara".

#!/bin/bash firstString="I love Suzi and Marry" secondString="Sara" # do something...

The result must be like this:

firstString="I love Sara and Marry"

回答1:

To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}:

#!/bin/bash firstString="I love Suzi and Marry" secondString="Sara" echo "${firstString/Suzi/$secondString}"    # prints 'I love Sara and Marry'

To replace all occurrences, use ${parameter//pattern/string}:

message='The secret code is 12345' echo "${message//[0-9]/X}"           # prints 'The secret code is XXXXX'

(This is documented in the Bash Reference Manual, §3.5.3 "Shell Parameter Expansion".)

Note that this feature is not specified by POSIX ― it's a Bash extension ― so not all Unix shells implement it. For the relevant POSIX documentation, see The Open Group Technical Standard Base Specifications, Issue 7, the Shell & Utilities volume, §2.6.2 "Parameter Expansion".



回答2:

This can be done entirely with bash string manipulation:

first="I love Suzy and Mary" second="Sara" first=${first/Suzy/$second}

That will replace only the first occurrence; to replace them all, double the first slash:

first="Suzy, Suzy, Suzy" second="Sara" first=${first//Suzy/$second} # first is now "Sara, Sara, Sara"


回答3:

try this:

 sed "s/Suzi/$secondString/g" <<<"$firstString"


回答4:

It's better to use bash than sed if strings have RegExp characters.

echo ${first_string/Suzi/$second_string}

It's portable to Windows and works with at least as old as Bash 3.1.

To show you don't need to worry much about escaping let's turn this:

/home/name/foo/bar

Into this:

~/foo/bar

But only if /home/name is in the beginning. We don't need sed!

Given that bash gives us magic variables $PWD and $HOME, we can:

echo "${PWD/#$HOME/\~}"

EDIT: Thanks for Mark Haferkamp in the comments for the note on quoting/escaping ~.*

Note how the variable $HOME contains slashes but this didn't break anything.

Further reading: Advanced Bash-Scripting Guide.
If using sed is a must, be sure to escape every character.



回答5:

for Dash all previous posts aren't working

for Dash:

result=$(echo $firstString | sed 's/Suzi/$secondString/g')


回答6:

If tomorrow you decide you don't love Marry either she can be replaced as well:

today=$( /tmp/lovers.txt

There must be 50 ways to leave your lover.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!