^word^replacement^ on all matches in Bash?

Solution 1:

Try this:

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

Solution 2:

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

Solution 3:

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

Solution 4:

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.