Linux command line 101 #1 : Here
Metacharacters are characters with a special use other than literal.
We have two types of metacharacters :
Substitution :
- * – (star) replace any character or group of characters.
- ? – (question mark) replace a character.
Protection :
Some examples of substitution :
I will use a directory containing the following files in my examples :
Sandrine-3:test sandrine$ ls -l
total 0
-rw-r--r-- 1 sandrine staff 0 6 jul 20:49 file_AA
-rw-r--r-- 1 sandrine staff 0 6 jul 21:13 file_Ab
-rw-r--r-- 1 sandrine staff 0 6 jul 21:13 file_Ac
-rw-r--r-- 1 sandrine staff 0 6 jul 20:49 file_bb
-rw-r--r-- 1 sandrine staff 0 6 jul 20:49 file_cc
-rw-r--r-- 1 sandrine staff 0 6 jul 20:49 files_1
-rw-r--r-- 1 sandrine staff 0 6 jul 21:15 files_2
-rw-r--r-- 1 sandrine staff 0 6 jul 21:15 files_3
Sandrine-3:test sandrine$
In this example, the “ls” command displays all files name with names starting with “files” with all possible endings :
Sandrine-3:test sandrine$ ls -l files*
-rw-r--r-- 1 sandrine staff 0 6 jul 20:49 files_1
-rw-r--r-- 1 sandrine staff 0 6 jul 21:15 files_2
-rw-r--r-- 1 sandrine staff 0 6 jul 21:15 files_3
Sandrine-3:test sandrine$
You can also do the opposite and find all files name that end with “_1” like this :
Sandrine-3:test sandrine$ ls -l *_1
-rw-r--r-- 1 sandrine staff 0 6 jul 20:49 files_1
Sandrine-3:test sandrine$
And with “?” you can search for all occurrences of files name beginning with “file_”, with an unknown character and ending with “b” like this :
Sandrine-3:test sandrine$ ls -l file_?b
-rw-r--r-- 1 sandrine staff 0 6 jul 21:13 file_Ab
-rw-r--r-- 1 sandrine staff 0 6 jul 20:49 file_bb
Sandrine-3:test sandrine$
Some examples of protective character uses :
If you wish to use the “echo” command to display a “*” you will get this :
Sandrine-3:test sandrine$ echo *
file_AA file_Ab file_Ac file_bb file_cc files_1 files_2 files_3
Sandrine-3:test sandrine$
To avoid interpretation of “*” as metacharacter precede it with the “\” :
Sandrine-3:test sandrine$ echo \*
*
Sandrine-3:test sandrine$
To force the interpretation of a character string placed it between backticks :
Sandrine-3:test sandrine$ echo ls
ls
Sandrine-3:test sandrine$ echo `ls`
file_AA file_Ab file_Ac file_bb file_cc files_1 files_2 files_3
Sandrine-3:test sandrine$
To avoid interpretation of a sting of metacharacters place it between quotes :
Sandrine-3:test sandrine$ echo ******
file_AA file_Ab file_Ac file_bb file_cc files_1 files_2 files_3
Sandrine-3:test sandrine$ echo '******'
******
Sandrine-3:test sandrine$