One of my favorite Unix tricks is ^x^y, which will take the last command and replace the first instance of “x” with “y”. However, I’m wondering if a similar trick works to replace all instances of “x” with “y” in the last command?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use the !!:gs/search/replace/ notation to do what you want. This utilizes the global search & replace (:gs):
before
$ echo "harm warm swarm barm" harm warm swarm barm
after
$ !!:gs/arm/orn/ echo "horn worn sworn born" horn worn sworn born
References
Method 2
I don’t believe there’s an easy way to add something to ^string1^string2 to make bash replace every occurrence. As slm points out, you have to write !!:gs/string1/string1.
But in zsh, you can just add :G:
$ echo foo foo foo foo $ ^foo^bar^:G echo bar bar bar bar
In both bash and zsh, you can also use fc -s like this:
$ echo foo foo foo foo $ fc -s foo=bar echo bar bar bar bar
This is often made into an alias called r so you can just do:
$ echo foo foo foo foo $ r foo=bar echo bar bar bar bar
Method 3
I believe that the best option is to use “:&”
$ echo "dog cat dog" $ ^dog^cat^:& echo "cat cat cat" cat cat cat
But like Stéphane Chazelas commented below, this replaces just 2 occurrences. If you have more, you’d need to add more :&
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0