Metacharacters in Ubuntu

In this article, we would discuss how to use Metacharacters in Ubuntu to our advantage. The default shell in Ubuntu is Bourne Again Shell (SHELL). We can consider Metacharacters to be special purpose characters.

Metacharacters make our life easier when it comes to doing certain operations through a shell in Ubuntu. Also, using Metacharacters does improve our productivity too.

Let’s understand these with the help of appropriate examples.

I. * (Asterisk) – If we want to know all the files and directories in our /home/$USER directory starting with “D”¬†character. Then, one option is –

ls ~

It will list the contents. And, from there we can figure out what all files and directories start with character “D“. But, when we have got Metacharacters at our disposal then this approach seems a bit odd. The efficient approach to such a problem is –

ls ~/D*

It will get us the desired result. In addition to, if we want to know all the file and directories which start with “D” character and end with ‘s‘. In that case do –

ls ~/D*s

Try placing different combinations with * and see how the outcome changes every time.

II. ? (Question Mark) – It is used to match patterns. For instance, if we want to know all the files which start with character “D”¬†and has a particular number of characters following it.

ls ~/D????????

Generally, we have two directories matching it –


III. > (Greater than) – It is used in cases where we want to store the output of a command to a file. For instance, we use cat command-line utility on /etc/hosts and store the output check.txt file. So,

cat /etc/hosts > check.txt

Note: The Metacharacter (>) deletes the content of the file every time we execute the above command. If we want to append the file then, we need to use Metacharacter (>>).

cat /etc/hosts >> check.txt

>> won’t replace the existing content of the file. And, inserts the output to the end of the file.

IV. { } (Brace expansion) – It is used to generate random strings.

echo ab{c,d,e}g

It would return with the output –

abcg abdg abeg

In conclusion, we have discussed Metacharacters in Ubuntu here. These come pretty handy in certain situations. And, make things easier for us. We would like to add here that, we have just covered four Metacharacters here. This is not everything about it. We will take this forward in subsequent articles.