^word^replacement^ 在 Bash 中的所有匹配项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/649070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:45:58  来源:igfitidea点击:

^word^replacement^ on all matches in Bash?

bashshellsh

提问by pisswillis

To clarify, I am looking for a way to perform a globalsearch and replace on the previous command used. ^word^replacement^only seems to replace the first match.

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

Is there some setoption that is eluding me?

有什么set选择让我望而却步吗?

回答by John Feminella

Try this:

尝试这个:

$ echo oneone
oneone
$ !!:gs/one/two/    # Repeats last command; substitutes 'one' --> 'two'.
twotwo

回答by Paused until further notice.

Blending my answer herewith John Feminella's you can do this if you want an alias:

融合了我的答案在这里与约翰Feminella的,如果你想要一个别名,你可以这样做:

$alias dothis='`history -p "!?monkey?:gs/jpg/png/"`'
$ls *.jpg
monkey.jpg
$dothis
monkey.png

The !! only does the previous command, while !?string? matches the most recent command containing "string".

这 !!只执行上一个命令,而 !?string? 匹配包含“string”的最新命令。

回答by l3x

This solution uses Bash Substring Replacement:

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

$ SENTENCE="1 word, 2 words";echo "${SENTENCE//word/replacement}"
1 replacement, 2 replacements

Note the use of the double slashes denotes "global" string replacement.

请注意,双斜线的使用表示“全局”字符串替换。

This solution can be executed in one line.

此解决方案可以在一行中执行。

Here's how to globally replace a string in a file named "myfile.txt":

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

$ sed -i -e "s/word/replacement/g" myfile.txt

回答by pisswillis

A nasty way to get around this could be something like this:

解决这个问题的一种讨厌的方法可能是这样的:

Want to echo BAABAArather than BLABLAby swapping L's for A's

想要回声BAABAA而不是BLABLA将 L 换成 A

$ echo "BLABLA"   
BLABLA
$ `echo "!!" | sed 's/L/A/g'`
$(echo "echo "BLABLA" " | sed 's/L/A/g')
BAABAA
$

Unfortunately this technique doesn't seem to work in functions or aliases.

不幸的是,这种技术似乎不适用于函数或别名。

回答by zhumaomao

I test it on SUSE 10.1. "^word^replacement^" doesn't work, while "^word^replacement" works well. for a instance:

我在 SUSE 10.1 上对其进行了测试。"^word^replacement^" 不起作用,而 "^word^replacement" 工作得很好。例如:

linux-geek:/home/Myworks # ls /etc/ld.so.conf   
/etc/ld.so.conf  
linux-geek:/home/Myworks # ^ls^cat  
cat /etc/ld.so.conf  
/usr/X11R6/lib/Xaw3d  
/usr/X11R6/lib  
/usr/i486-linux-libc5/lib=libc5  
/usr/i386-suse-linux/lib  
/usr/local/lib  
/opt/kde3/lib  
/opt/gnome/lib  
include /etc/ld.so.conf.d/*.conf  
linux-geek:/home/Myworks #