^字^替换^在Bash的所有比赛?

pis*_*lis 47 bash shell sh

为了澄清,我正在寻找一种方法来执行全局搜索并替换上一个使用的命令.^word^replacement^似乎只是取代了第一场比赛.

有什么set选择可以逃避我吗?

Joh*_*lla 64

试试这个:

$ echo oneone
oneone
$ !!:gs/one/two/    # Repeats last command; substitutes 'one' --> 'two'.
twotwo
Run Code Online (Sandbox Code Playgroud)


Pau*_*ce. 6

如果你想要一个别名,我可以在这里将我的答案与John Feminella相提并论:

$alias dothis='`history -p "!?monkey?:gs/jpg/png/"`'
$ls *.jpg
monkey.jpg
$dothis
monkey.png
Run Code Online (Sandbox Code Playgroud)

!! 只执行上一个命令,而!?string?匹配包含"string"的最新命令.


l3x*_*l3x 6

此解决方案使用Bash子串替换:

$ SENTENCE="1 word, 2 words";echo "${SENTENCE//word/replacement}"
1 replacement, 2 replacements
Run Code Online (Sandbox Code Playgroud)

请注意,使用双斜杠表示"全局"字符串替换.

该解决方案可以在一行中执行.

以下是如何全局替换名为"myfile.txt"的文件中的字符串:

$ sed -i -e "s/word/replacement/g" myfile.txt
Run Code Online (Sandbox Code Playgroud)