^word^replacement^ on all matches in Bash?

Viewed 11411

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?

6 Answers

Try this:

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

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

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.

this question has many dupes and one elegant answer only appears in this answer of user @Mikel in unix se

fc -s pat=rep

this bash builtin is documented under the chapter 9.2 Bash History Builtins

In the second form, command is re-executed after each instance of pat in the selected command is replaced by rep. command is interpreted the same as first above.

A useful alias to use with the fc command is r='fc -s', so that typing ‘r cc’ runs the last command beginning with cc and typing ‘r’ re-executes the last command (see Aliases).

Related