Showing posts with label Bash Wildcards. Show all posts
Showing posts with label Bash Wildcards. Show all posts

Standard Wildcards

Wildcards are useful in many ways for a GNU/Linux system and for various other uses. Commands can use wildcards to perform actions on more than one file at a time, or to find part of a phrase in a text file. There are many uses for wildcards, there are two different major ways that wildcards are used, they are globbing patterns/standard wildcards that are often used by the shell. The alternative is regular expressions, popular with many other commands and popular for use with text searching and manipulation.
Tip: If you have a file with wildcard expressions in it then you can use single quotes to stop bash expanding them or use backslashes (escape characters), or both.
For example if you wanted to create a file called 'fo*' (fo and asterisk) you would have to do it like this (note that you shouldn't create files with names like this, this is just an example):
  touch 'fo*' 
  
Note that parts of both subsections on wildcards are based (at least in part) off the grep manual and info pages.

Standard Wildcards (globbing patterns)

Standard wildcards (also known as globbing patterns) are used by various command-line utilities to work with multiple files. For more information on standard wildcards (globbing patterns) refer to the manual page by typing:
man 7 glob
Can be used by: Standard wildcards are used by nearly any command (including mv, cp, rm and many others).
? (question mark)
this can represent any single character. If you specified something at the command line like "hd?" GNU/Linux would look for hda, hdb, hdc and every other letter/number between a-z, 0-9.
* (asterisk)
this can represent any number of characters (including zero, in other words, zero or more characters). If you specified a "cd*" it would use "cda", "cdrom", "cdrecord" and anything that starts with “cd” also including “cd” itself. "m*l" could by mill, mull, ml, and anything that starts with an m and ends with an l.
[ ] (square brackets)
specifies a range. If you did m[a,o,u]m it can become: mam, mum, mom if you did: m[a-d]m it can become anything that starts and ends with m and has any character a to d inbetween. For example, these would work: mam, mbm, mcm, mdm. This kind of wildcard specifies an “or” relationship (you only need one to match).
{ } (curly brackets)
terms are separated by commas and each term must be the name of something or a wildcard. This wildcard will copy anything that matches either wildcard(s), or exact name(s) (an “or” relationship, one or the other).
For example, this would be valid:
cp {*.doc,*.pdf} ~
This will copy anything ending with .doc or .pdf to the users home directory. Note that spaces are not allowed after the commas (or anywhere else).
[!]
This construct is similar to the [ ] construct, except rather than matching any characters inside the brackets, it'll match any character, as long as it is not listed between the [ and ]. This is a logical NOT. For example rm myfile[!9] will remove all myfiles* (ie. myfiles1, myfiles2 etc) but won't remove a file with the number 9 anywhere within it's name.
\ (backslash)
is used as an "escape" character, i.e. to protect a subsequent special character. Thus, "\\” searches for a backslash. Note you may need to use quotation marks and backslash(es).

Regular Expressions

Regular expressions are a type of globbing pattern used when working with text. They are used for any form of manipulation of multiple parts of text and by various programming languages that work with text. For more information on regular expressions refer to the manual page or try an online tutorial, for example IBM Developerworks using regular expressions. For the manual page type:
Type:
man 7 regex
Regular expressions can be used by: Regular Expressions are used by grep (and can be used) by find and many other programs.
Tip: If your regular expressions don't seem to be working then you probably need to use single quotation marks over the sentence and then use backslashes on every single special character.
. (dot)
will match any single character, equivalent to ? (question mark) in standard wildcard expressions. Thus, "m.a" matches "mpa" and "mea" but not "ma" or "mppa".
\ (backslash)
is used as an "escape" character, i.e. to protect a subsequent special character. Thus, "\\" searches for a backslash. Note you may need to use quotation marks and backslash(es).
.* (dot and asterisk)
is used to match any string, equivalent to * in standard wildcards.
* (asterisk)
the proceeding item is to be matched zero or more times. ie. n* will match n, nn, nnnn, nnnnnnn but not na or any other character.

^ (caret)
means "the beginning of the line". So "^a" means find a line starting with an "a".
$ (dollar sign)
means "the end of the line". So "a$" means find a line ending with an "a".
For example, this command searches the file myfile for lines starting with an "s" and ending with an "n", and prints them to the standard output (screen):
cat myfile | grep '^s.*n$'
 
[ ] (square brackets)
specifies a range. If you did m[a,o,u]m it can become: mam, mum, mom if you did: m[a-d]m it can become anything that starts and ends with m and has any character a to d inbetween. For example, these would work: mam, mbm, mcm, mdm. This kind of wildcard specifies an “or” relationship (you only need one to match).
|
This wildcard makes a logical OR relationship between wildcards. This way you can search for something or something else (possibly using two different regular expressions). You may need to add a '\' (backslash) before this command to work, because the shell may attempt to interpret this as a pipe.

[^]
This is the equivalent of [!] in standard wildcards. This performs a logical “not”. This will match anything that is not listed within those square brackets. For example, rm myfile[^9] will remove all myfiles* (ie. myfiles1, myfiles2 etc) but won't remove a file with the number 9 anywhere within it's name.

Useful categories of characters (as defined by the POSIX standard)

This information has been taken from the grep info page with a tiny amount of editing,
  • [:upper:] uppercase letters
  • [:lower:] lowercase letters
  • [:alpha:] alphabetic (letters) meaning upper+lower (both uppercase and lowercase letters)
  • [:digit:] numbers in decimal, 0 to 9
  • [:alnum:] alphanumeric meaning alpha+digits (any uppercase or lowercase letters or any decimal digits)
  • [:space:] whitespace meaning spaces, tabs, newlines and similar
  • [:graph:] graphically printable characters excluding space
  • [:print:] printable characters including space
  • [:punct:] punctuation characters meaning graphical characters minus alpha and digits
  • [:cntrl:] control characters meaning non-printable characters
  • [:xdigit:] characters that are hexadecimal digits.
These are used with: The above commands will work with most tools which work with text (for example: tr).
For example (advanced example), this command scans the output of the dir command, and prints lines containing a capital letter followed by a digit:


ls -l | grep '[[:upper:]][[:digit:]]'
 
The command greps for [upper_case_letter][any_digit], meaning any uppercase letter followed by any digit. If you remove the [ ] (square brackets) in the middle it would look for an uppercase letter or a digit, because it would become [upper_case_letter any_digit].

Bash Wildcards - 8 Practical Examples

Globbing is nothing but path-name expansion and wildcards are used to perform globbing on Linux command line. Here, in this article, we will discuss how wild-cards can be used to make life easy for a command line user. Please note that it is the shell (bash in this case) that does the required globbing. Neither OS, nor the executed program processes wild-cards in any way.
NOTE – All the examples in this article are tested on bash shell in Ubuntu 13.04.

Bash Wildcards - Simple Globbing

In this section, we will discuss simple examples of the following four commonly used bash wildcards:
  • Asterisk – *
  • Question Mark – ?
  • Square Brackets – []
  • Curly Brackets – {}

Q1. Is there something that represents any number of characters?

Ans. Yes. An asterisk (*) can be replaced with any number of characters. It is one of the most popular wildcard character and is extremely useful in cases where you don’t care what replaces it as long as the main search condition is true. For example – if you want to list all the files that have a .c extension then you can use *.c as argument to ls command. Here, file name does not matter and so an asterisk is used as a wildcard for file-name.
Here is an example screen-shot:
asterisk
So you can see that the asterisk (*) wildcard was replaced by the file names.

Q2. Is there something that represents only one character?

Ans. Yes, a question mark (?) can be replaced with a single character. This wildcard is useful in scenarios where file names are similar except a single character. For example, if there are 10 log files (log1.txt, log2.txt and so on) then to list down the details of all the files or to perform any other operation collectively on these files you can use log?.txt.
Here is an example screen-shot :
questionMark
So you can see that the question mark (?) wildcard was replaced by a single character (a number in this example).

Q3. Is there something that represents a range of characters?

Ans. Yes, square brackets can be used to specify a particular range. This wildcard is especially useful when it is desired to filter out file names based on a set of characters. For example, to delete only log1.txt, log2.txt and log3.txt out of all the five log files (created in previous example), just use log[1-3].txt.
Here is an example screen-shot :
square-bracket
This command should delete log1.txt, log2.txt and log3.txt. Lets confirm it using the question mark wildcard that was discussed in previous example:
question-mark
So you can see that only log4.txt and log5.txt are listed in the output. This means that the other 3 files were successfully removed through square bracket wildcard [].

Q4. Is there something that cut shorts repetitive work on command line?

Ans. Yes, curly brackets {}  can be used to specify only the variable parts (separated by comma) of multiple commands and hence they cut short writing long or repetitive commands. For example, to create three files log1, log2 and log3, either you will write touch command thrice or you will write something like touch log1.txt log2.txt log3.txt. But, this effort can be further cut short by using curly brackets. Just write touch log{1,2,3}.txt.
Here is an example screen-shot :
curlyBrackets
This command should create three files – log1.txt, log2.txt and log3.txt. Lets confirm it using ls command :
question-mark-1
So you can see that all the three files were created successfully.

Bash Wildcards - Extended Globbing

In this section, we will discuss some advanced examples of globbing through pattern list matching using the following patterns:
  • ?(… | …)   -  Match zero or one occurrence of the items listed between the pipes (|)
  • *(… | …)   -  Match zero or more occurrence of the items listed between the pipes (|) 
  • +(… | …)   -  Match one or more occurrence of the items listed between the pipes (|)
  • !(… | …)   -  Match anything except the items listed between the pipes (|)

Q1. How to search one or more occurrence of files based on initial few characters of the file names?

Ans. The pattern +(…|…) can be used in this case. Here is an example screen-shot :
pattern+
So you can see that the pattern +(fi|fr)* was used with ls command to produce the desired results. If you try to break down the expression then +(fi|fr) represents one or more occurrence of files having fi or fr as initial characters in names and the trailing asterisk (*) can be replaced with any number of characters i.e., effectively the remaining part of file names.
Similarly you can use ?(…|…) to match zero or one items and *(…|…) to match zero or more items present between pipes (|).

Q2. How to search all the file names except some files that have a known name pattern?

Ans. To discuss the solution to this problem, you can take the file name pattern from the previous example. So, the task is to display names of all the files (present in current directory) while filtering out those having fi or fr as initial characters in names. The pattern !(…|…) can be used in this case.
Here are all the contents that are present in current directory :
dir-contents
Here is the command that filters the required file names and displays the rest:
negate
So you can see that the wildcard expression !(…|…) can be used for filtering purpose.

Important Points To Remember

1. Do check the man page of grep command to explore predefined named classes of characters within bracket expressions.
Here is a screen-shot from the man page of grep command:
grep
Here is a brief information about these predefined classes :
  • [:upper:]  -> Match uppercase characters
  • [:lower:]   -> Match lowercase characters
  • [:alpha:]   -> A super set of [:upper:] + [:lower:]
  • [:digit:]     -> Match decimal numbers ie 0 to 9
  • [:alnum:]  -> A super set of [:alpha:] + [:digit:]
  • [:space:]   -> Match spaces, newlines, tabs etc
  • [:graph:]  -> Match characters (excluding space) that are graphically printable
  • [:print:]    -> Match characters (including space) that are printable
  • [:punct:]   -> Match punctuation characters ie [:graph:] – ([:alpha:] + [:digit:])
  • [:cntrl:]    -> Match non-printable control characters
  • [:xdigit:]  -> Match hexadecimal digits
Here is an example that demonstrates the usage of these predefined named classes of characters:
digit-character-set
So you can see that the class digit matched all the decimal numbers.
2. All the wild-card techniques described here are bash shell specific. Keep this in mind especially if you are a programmer who wants to use wildcards from within his/her program code(using exec() family of functions) as wild card expansions may not work if the program is executed in non-bash shells.

HowTo Create Files in Linux From a Bash Shell Prompt

I'm a new to CentOS Linux user. How do I create a file from bash prompt without using GUI tools?

Linux / UNIX like operating system offers many command line tools and text editors for creating text files. You can use vi or joe text editor. It is a terminal-based text editor for Linux/Unix like systems, available under the GPL. It is designed to be easy to use. In short, you can use any one of the following tool:










  1. cat command
  2. echo or printf command
  3. vi text editor
  4. joe text editor
  5. Any other console based text editor

Create a Text File using cat command

To create a text file called foo.txt, enter:

$ cat > foo.txt

Output:

This is a test.
Hello world!
press CTRL+D to save file
 
To display file contents, type:

$ cat foo.txt

Create a text file using echo or printf

To create a file called foo.txt, enter:
 
echo 'This is a test' > foo.txt
 
OR
 
printf 'This is a test\n' > foo.txt
 
OR
 
printf 'This is a test\n Another line' > foo.txt
 
To display file contents, type:

 $ cat foo.txt

Create a Text File using joe text editor

JOE is text editor. To create a file called foo.txt, type:

 $ joe -help foo.txt


You will see help menu on screen. Next type something. To save the file and leave joe, by typing ^KX (press CTRL+K+X).

Create a Text File using vi / vim text editor

vi / vim is another text editor. To create a file called bar.txt, type:

$ vi bar.txt

Press 'i' to insert new text. To save the file and leave vi, type ESC+:+x (press ESC key, type : followed by x and [enter] key).