Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
1  
The feature is called history expansion. Looks like we use the command-history tag for that. Added. Also, I assume you're referring to the bash shell? –  Mikel Feb 24 at 3:06
    
Yeah, I was referencing bash. Thanks! –  Mason Feb 24 at 3:54
add comment

2 Answers 2

up vote 20 down vote accepted

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

share|improve this answer
1  
Awesome, thanks! –  Mason Feb 24 at 3:53
1  
@slm this command is replacing just the first instance for me . [subhrcho@slc04lyo pcbpel]$ echo "hat that bat" hat that bat [subhrcho@slc04lyo pcbpel]$ !!:gs/at/xx/ echo "hxx that bat" hxx that bat. What am I missing? –  Geek Feb 24 at 6:35
    
@Geek - what's your distro? Are you using Bash? Version? bash --version = 4.2.45(1)-release. –  slm Feb 24 at 6:39
    
@slm GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu) Copyright (C) 2005 Free Software Foundation, Inc. –  Geek Feb 24 at 6:40
    
@Geek - too old a version, doesn't offer this feature. –  slm Feb 24 at 6:41
show 1 more comment

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
share|improve this answer
    
Wow, this is really neat too –  Mason Feb 24 at 3:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.