Search and replace commands from terminal history

I would like to know how / if I can reuse the command from the history of my terminal, but in a modified version. Here is 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 just access the command from the history and manually replace the two 2s, but is there a more elegant way?

Thanks so much for your time!

+5
source share
1 answer

If there is only one instance of what you want to replace, it bash(1)has an easy function first introduced in csh(1):

^old^new

will replace the first instance oldwith new:

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

If you want to replace all instances, this requires more input:

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

g . ! - , . . bash(1) Event Designators.

+12

All Articles