bash-logo

Sometimes we use Linux commands with many long arguments, and to use the same command with a little modification we are obliged to go through these args and modify them one by one.
Example :

touch /home/user1/test/scenario.txt  /etc/my-server/users/user1.cnf /var/log/my-server/user1.log

What will I do if I want to do the same to user2?

To replace all occurrences in the last command you can use the command below:

!:gs/old_occurrence/new_occurrence

!refers to the last command
gs refers to global substitute
To replace a word you can use the command below:

^old_word^new_word

Examples:

[www1.linuxnix] root:~ # touch test1 scenario1 result1
[www1.linuxnix] root:~ # !:gs/1/2
touch test2 scenario2 result2
[www1.linuxnix] root:~ # ls -l test* scenario* result*
-rw-r--r-- 1 root root 0 Nov 20 16:45 result1
-rw-r--r-- 1 root root 0 Nov 20 16:45 result2
-rw-r--r-- 1 root root 0 Nov 20 16:45 scenario1
-rw-r--r-- 1 root root 0 Nov 20 16:45 scenario2
-rw-r--r-- 1 root root 0 Nov 20 16:45 test1
-rw-r--r-- 1 root root 0 Nov 20 16:45 test2
[www1.linuxnix] root:~ # mkdir -p tests/exp/scenario1/tools/
[www1.linuxnix] root:~ # ^exp^lab
mkdir -p tests/lab/scenario1/tools/
[www1.linuxnix] root:~ # tree tests
tests
├── exp
│   └── scenario1
│       └── tools
└── lab
    └── scenario1
        └── tools

6 directories, 0 files

Note: when you use ^^ with multiple occurrences, only the first occurrence is replaced.
Example:

[www1.linuxnix] root:~ # ls -l test1 scenario1 result1
-rw-r--r-- 1 root root 0 Nov 20 16:45 result1
-rw-r--r-- 1 root root 0 Nov 20 16:45 scenario1
-rw-r--r-- 1 root root 0 Nov 20 16:45 test1
[www1.linuxnix] root:~ # ^1^2
ls -l test2 scenario1 result1
-rw-r--r-- 1 root root 0 Nov 20 16:45 result1
-rw-r--r-- 1 root root 0 Nov 20 16:45 scenario1
-rw-r--r-- 1 root root 0 Nov 20 16:45 test2

Replace the last word in history

Suppose we executed below command and want to replace ls with the cat to see the content we can use bash shortcuts either !$ or $_ for this.

ls -l /etc/passwd

cat $_  or cat !$

I hope that this blog helped you. Please visit our website for other interesting blogs and feel free to leave your feedbacks and thoughts. Till next time!

The following two tabs change content below.
I am a hands-on, competent Linux system engineer with 9 years’ experience. I have a strong performance background in wide variety of professional Linux system support including monitoring, configuration, troubleshooting and maintenance. I have worked on numerous projects from concept to completion. A specialist in LAMP platforms, I take pride in administrating Linux systems and regularly refresh my skills to ensure I keep up with ongoing developments and new technologies.