24.07.2018 Views

Bash-Beginners-Guide

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

cheesecloth<br />

cheetah<br />

--output omitted--<br />

If you want to find the literal asterisk character in a file or output, use single quotes. Cathy in the example<br />

below first tries finding the asterisk character in /etc/profile without using quotes, which does not<br />

return any lines. Using quotes, output is generated:<br />

cathy ~> grep * /etc/profile<br />

cathy ~> grep '*' /etc/profile<br />

for i in /etc/profile.d/*.sh ; do<br />

4.3. Pattern matching using <strong>Bash</strong> features<br />

4.3.1. Character ranges<br />

Apart from grep and regular expressions, there's a good deal of pattern matching that you can do directly in<br />

the shell, without having to use an external program.<br />

As you already know, the asterisk (*) and the question mark (?) match any string or any single character,<br />

respectively. Quote these special characters to match them literally:<br />

cathy ~> touch "*"<br />

cathy ~> ls "*"<br />

*<br />

But you can also use the square braces to match any enclosed character or range of characters, if pairs of<br />

characters are separated by a hyphen. An example:<br />

cathy ~> ls -ld [a-cx-z]*<br />

drwxr-xr-x 2 cathy cathy 4096 Jul 20 2002 app-defaults/<br />

drwxrwxr-x 4 cathy cathy 4096 May 25 2002 arabic/<br />

drwxrwxr-x 2 cathy cathy 4096 Mar 4 18:30 bin/<br />

drwxr-xr-x 7 cathy cathy 4096 Sep 2 2001 crossover/<br />

drwxrwxr-x 3 cathy cathy 4096 Mar 22 2002 xml/<br />

This lists all files in cathy's home directory, starting with "a", "b", "c", "x", "y" or "z".<br />

If the first character within the braces is "!" or "^", any character not enclosed will be matched. To match the<br />

dash ("-"), include it as the first or last character in the set. The sorting depends on the current locale and of<br />

the value of the LC_COLLATE variable, if it is set. Mind that other locales might interpret "[a-cx-z]" as<br />

"[aBbCcXxYyZz]" if sorting is done in dictionary order. If you want to be sure to have the traditional<br />

interpretation of ranges, force this behavior by setting LC_COLLATE or LC_ALL to "C".<br />

4.3.2. Character classes<br />

Character classes can be specified within the square braces, using the syntax [:CLASS:], where CLASS is<br />

defined in the POSIX standard and has one of the values<br />

"alnum", "alpha", "ascii", "blank", "cntrl", "digit", "graph", "lower", "print", "punct", "space", "upper", "word"<br />

or "xdigit".<br />

Some examples:<br />

Chapter 4. Regular expressions 60

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!