Sample Header Ad - 728x90

Using bash history expansion, can you replace the first argument of the last time a command ran, when it's not the most recent command?

1 vote
2 answers
63 views
The GNU History Expansion reference lacks examples, so I can't tell if this is possible. Here's what I want to do. I ran cat long/path/to/file1.txt | less, then I ran vim file2.txt. Using history expansion, I'd like to run cat even/longer/path/to/file3.txt | less but I don't want to: - Type long/path/to/file1.txt, since it's inconvenient to type. - Refer to the previous command with a number; I want to refer to it with a string. i.e., Use !cat..., but not !-2... Can this be done? --- Here's what I've tried (doesn't work): !cat:^!cat:1^even/longer/path/to/file3.txt^ Here's my thought process: 1. !cat - Substitute the last *command* that began with the string cat. 1. :^x^y^ - Replace x with y in this command 1. !cat:1 - Expand to the first argument of the last cat command, i.e., long/path/to/file1.txt 1. even/longer/path/to/file3.txt – The replacement for that expanded text One obvious reason this doesn't work is I'm nesting expansions in expansions: !cat:1 is interpreted as a literal string. I get this output: long/path/to/file1.txtlong/path/to/file1.txteven/longer/path/to/file3.txt^: No such file or directory
Asked by Daniel Kaplan (1070 rep)
Apr 1, 2025, 06:58 PM
Last activity: Apr 2, 2025, 07:12 AM