Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do search and replace on commands from terminal history

Tags:

linux

shell

unix

I would like to know how/if I can reuse a command from my terminal history, but in a modified version. Here's an example:

$ filter_script file2 > output_file2
$ # ...
# now run the same command, but replace '2' with '4'
$ filter_script file4 > output_file4

This is a very simple example, and of course I can simply access the command from the history and manually replace the two 2s, but is there a more elegant way?

Thanks a lot for your time!

like image 895
canavanin Avatar asked Nov 22 '11 09:11

canavanin


1 Answers

If there's only one instance of whatever it is you want replaced, bash(1) has an easy feature first introduced in csh(1):

^old^new

will replace the first instance of old with new:

$ filter_script file2 > output_file2
$ ^2^4
filter_script file4 > output_file2

If you want to replace all the instances, that requires more typing:

$ filter_script file2 > output_file2
$ !:gs/2/4/
filter_script file4 > output_file4

The g specifies the global replacement on the command line. The ! refers to a line from history -- which could be more specific, if you wanted to pull a command from further back in history that the immediately previous command. See bash(1)'s section on Event Designators.

like image 110
sarnold Avatar answered Oct 09 '22 03:10

sarnold