23

Occasionally I use the bash command to replace string in previous command:

^foo^bar

Today I wanted to make the replacement in the following line for replacing all occurrences of checkbox with `radio:

$ git mv _product_checkbox_buttons.html.erb _product_checkbox_button.html.erb
$ ^checkbox^radio
git mv _product_radio_buttons.html.erb _product_checkbox_button.html.erb

So it only replaces the first occurrence. How do I make it replace all occurrences?

bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin10.0)
Copyright (C) 2007 Free Software Foundation, Inc.
Jesper Rønn-Jensen
  • 106,591
  • 44
  • 118
  • 155

2 Answers2

33

man bash says ^old^new is equivalent to !!:s/old/new/. You want !!:gs/old/new/ to globally replace.

dubiousjim
  • 4,722
  • 1
  • 36
  • 34
  • Thanks a lot! AT this point, bash commands suddenly appear very ugly and non-readable. But it's amazing what you can do ! – Jesper Rønn-Jensen Feb 17 '10 at 13:56
  • I agree! That g definitely belongs at the end! – dubiousjim Feb 17 '10 at 13:58
  • 1
    Yeah, I pretty sure you want !!:s/old/new/g, so in the case of the original questioner, you want !!:s/checkbox/radio/g – Jim Feb 17 '10 at 17:29
  • 5
    @Jim, yeah that's how it should work, but it doesn't. Bash history demands the g at the start, not at the end. Putting it at the end will do a single substitution only, followed by a literal "g". Try it. – dubiousjim Feb 17 '10 at 18:34
  • @jesper, you are trying to use the c-shell based syntax. maybe have a look at the vi or emacs command line editing interface. much more powerful. – Rob Wells Feb 18 '10 at 19:01
14

An easy way of doing this would be:

fc -s checkbox=radio

I have an alias r defined in my .bashrc:

alias r='fc -s'

Then what you want to do becomes:

r checkbox=radio

See my answer to "hidden features of bash" question for details.

Community
  • 1
  • 1
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
  • This should be **the** answer, as it is so easy to remember and otherwise I have google every time I need to do this. – xpt Nov 02 '16 at 16:08
  • I like this over `^foo^bar^` and `!!:gs/foo/bar/` because I can easily put this into an alias. I frequently want to run a modified version of a command, not just fix a typo, and this makes the process smoother – dwanderson May 01 '18 at 18:51