Correct/Repeat the last command under Bash

By | September 23, 2014

If you often type the wrong command (or repeat the simmilar commends) under bash shell (like me), you may need to read this post:

cp file1.txt /path/to/dst
cp file1.a1 /path/to/dst
cp file1.a2 /path/to/dst

Substitute the first occurrence

How do I replace .txt with a1 and a2 and repeat the last command? The syntax is as follows for quick substitution and repeat the last command, replacing WORD1 with WORD2:

^WORD1^WORD2^

which is equivelent to

!!:s/WORD1/WORD2

Therefore, ^.txt^.a1 will generate the second commend above, and ^.a1^.a2 will generate the third one.

Substitute all occurrences

The above syntax substitutes only applies to the first occurrence. For example:

cp file1.txt /path/to/dst/file1.txt
^.txt^.a1

# Output:
cp file1.a1 /path/to/dst/file1.txt

To repeat the last command with a substitution, use

!!:gs/WORD1/WORD2

For example:

cp file1.txt /path/to/dst/file1.txt
!!:s/.txt/.a1

# Output:
cp file1.a1 /path/to/dst/file1.a1

Leave a Reply

Your email address will not be published. Required fields are marked *