[SATLUG] character classes with *

Wes Henderson whendersonii at gmail.com
Wed Oct 1 16:46:57 CDT 2014

Here are some examples for you to mull over. Just run the command starting
with 'cat' and ending with the second 'EOF' to create the file I am
demonstrating with. I am using --color with grep to highlight what is

cat > ~/test_file << EOF
This is my test file.
I am using it to learn a bit about RegEX.
I sincerely hope it proves fruitful. ^5

This will return only line 3 (the entire line) as it is the only line with
a number:
grep [1-9] test_file --color

If you want to match ONLY the number then add -o:
grep -o [1-9] test_file --color

Conversely you can see that the following command will return the entire
grep "[a-z]" test_file --color
NOTE: The --color option will show you that the capital letters and
punctuation are not matched, but they are on lines that are matched.

If you want to match capital letters as well you can do the following:
grep "[a-Z]" test_file --color
NOTE: [a-Z] catches all lower case and capital letters; refer to ASCII
chart for better understanding.

Lets try a slightly different example:

cat > ~/test_file << EOF
#This is my test file.
#I am using it to learn a bit about RegEX.
#I sincerely hope it proves fruitful. ^5

#This is a mock config file.

#Fake data to follow.
* 5 * 6 7 root curl -skL testsite.com/example.php

#End of data.

In this case I want to take out all blank lines from the newly modified
grep -v ^$ test_file
NOTE: -v means opposite; ^ means starts with; $ means ends with. I am
telling grep to pull everything that contains characters.

Now I want to pull all non-blank, non-comment lines from the file:
grep -v ^$ test_file|grep -v ^\#

Now I want to pull all lines that have data inside [*]:
grep -v ^$ test_file|grep -v ^\#|grep -v "\[*\]"

Now, for bonus point I want to format my cron style entry in a human
readable sentence:
grep -v ^$ test_file|grep -v ^\#|grep -v "\[*\]"| awk -v sq=\' '{print "For
every day of the month during June (" $4 ") on Sunday (" $5 "), every
minute during the " $2 " o" sq "clock hour " $6 " will run "sq $7 " " $8 "
" $9 sq "!"}'
NOTE: This obviously is not meant to be anything practical, it was just a
really quick, silly example.

Hope these examples lend a hand.

More information about the SATLUG mailing list