Question

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

Is there some set option that is eluding me?

Was it helpful?

Solution

Try this:

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

OTHER TIPS

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

$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".

This solution uses Bash Substring Replacement:

$ 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":

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

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

Want to echo BAABAA rather than BLABLA by swapping L's for A's

$ 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.

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

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 #   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top