Sometimes I run a command and immediately realize I only need to change one small part of it.
For example, say I just converted a video with ffmpeg:
ffmpeg -i calligraphy01.mp4 -c:v libx264 -c:a aac calligraphy_good_01.mp4
Then I want to run the same command for the next file:
ffmpeg -i calligraphy02.mp4 -c:v libx264 -c:a aac calligraphy_good_02.mp4
Instead of pressing the up arrow and manually editing both places, in zsh I can type:
!!:gs/01/02/
That means:
Take the previous command, replace every
01with02, and run it.
So this:
!!:gs/01/02/
expands to:
ffmpeg -i calligraphy02.mp4 -c:v libx264 -c:a aac calligraphy_good_02.mp4
What the syntax means
!!
means “the previous command”.
:gs/01/02/
means “globally substitute 01 with 02”.
So the full command:
!!:gs/01/02/
means:
Use the last command, replace all
01with02, then execute it.
Preview before running
Sometimes I do not want to run it immediately. I want to see the expanded command first.
For that, add :p:
!!:gs/01/02/:p
This prints the modified command without executing it:
ffmpeg -i calligraphy02.mp4 -c:v libx264 -c:a aac calligraphy_good_02.mp4
Then, if the command looks correct, press the up arrow to bring that printed command back into the prompt, review it one more time, and press Enter to run it.
So the safer workflow is:
!!:gs/01/02/:p
Check the output, then:
Up Arrow → review command → Enter
This is useful when the command is long, destructive, or expensive to run.
Replace only the first match
If you only want to replace the first occurrence, you can use:
^01^02
But for commands like this ffmpeg example, where the number appears in both the input and output filename, !!:gs/01/02/ is usually what you want.
Tiny shell tricks like this save only a few seconds each time, but they make repeated command-line work feel much smoother.
Top comments (0)