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!
Latest posts by ZIADI Mohamed Ali (see all)
- How to show mounted devices in Linux? - July 25, 2017
- How to use Positional parameters and special variables in Linux - June 28, 2017
- Linux: Connect to your WiFi network through CLI? - June 25, 2017
- How to find a file in Linux? - March 19, 2017
- Mysql: How to find table and database size? - January 9, 2017