Skip navigation

If you’ve been working with the Unix command-line for any length of time, you likely know about using ‘^’ to replace some part of the previous command with new text. Here’s a typical example

 $ ls dir-09-14-2011/*.log [lots of output here] $ ^14^13 ls dir-09-13-2011/*.log [logs of output here]

This works fine when you only want to replace one instance of what you’re working with, but what do you do in this example?

 $ mv dir-09-14-2011 backup-09-14-2011

If you try the same trick this time, you’ll get this.

 $ ^14^13 mv dir-09-13-2011 backup-09-14-2011

Not what we want. What’s a budding command-line hacker to do? If only there was a way to do a global replacement of one item for another on the command line.  Well, if you’re using bash, there is.

 $ mv dir-09-14-2011 backup-09-14-2011  $ !!:gs/-14-/-13-/ mv dir-09-13-2011 backup-09-13-2011

Using this method, you can do a global substitution of one term for another.  In this instance, I show my extra paranoia by replacing ‘-14-‘ with ‘-13-‘ to make sure there are no inadvertent replacements.  It would have worked just as well with ‘!!:gs/14/13/’ in this particular instance, but I’ve found paranoia is a good thing when futzing around on the command line, especially when you’re working with ‘rm’ and ‘mv’. So, hope that helps you in your future endeavors on the command line!