Bash – How to apply caret-substitution to the nth-last command

bashcommand line

I regularly find myself having to execute a lengthy command on a file, then process the results with other commands. To process the next file, I usually rerun the same command by hitting the Up key until I find the command I want and arduously replace the old filename with the new filename.

Is there a way to combine caret substitution (^oldfile^newfile) with the n th-last command? I have (unsuccessfully) tried to pipe the n th-last command into the substitution like so:

$ !-4 | ^old^new

Of course, I am open to other suggestions. These little shortcuts really help with productivity…

Best Answer

You can't do it with a quick substitution directly, because ^foo^bar is shorthand for:

!!:s/foo/bar/

The !! part (which refers to the last command) isn't part of the quick syntax (that's what makes it quick), but you can use the longer syntax directly and then modify the !! to whatever you want:

!-4:s/foo/bar/

I explained as much of the history syntax as I know in this post; the last section includes the :s modifier