27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

grep −c txt *.sgml<br />

# (number of occurrences of "txt" in "*.sgml" files)<br />

# grep −cz .<br />

# ^ dot<br />

# means count (−c) zero−separated (−z) items matching "."<br />

# that is, non−empty ones (containing at least 1 character).<br />

#<br />

printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep −cz . # 4<br />

printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep −cz '$' # 5<br />

printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep −cz '^' # 5<br />

#<br />

printf 'a b\nc d\n\n\n\n\n\000\n\000e\000\000\nf' | grep −c '$' # 9<br />

# By default, newline chars (\n) separate items to match.<br />

# Note that the −z option is GNU "grep" specific.<br />

# Thanks, S.C.<br />

When invoked with more than one target file given, grep specifies which file contains matches.<br />

bash$ grep Linux osinfo.txt misc.txt<br />

osinfo.txt:This is a file containing information about Linux.<br />

osinfo.txt:The GPL governs the distribution of the Linux operating system.<br />

misc.txt:The Linux operating system is steadily gaining in popularity.<br />

To force grep to show the filename when searching only one target file, simply give<br />

/dev/null as the second file.<br />

bash$ grep Linux osinfo.txt /dev/null<br />

osinfo.txt:This is a file containing information about Linux.<br />

osinfo.txt:The GPL governs the distribution of the Linux operating system.<br />

If there is a successful match, grep returns an exit status of 0, which makes it useful in a condition test<br />

in a script, especially in combination with the −q option to suppress output.<br />

SUCCESS=0<br />

word=Linux<br />

filename=data.file<br />

grep −q "$word" "$filename"<br />

# if grep lookup succeeds<br />

# The "−q" option causes nothing to echo to stdout.<br />

if [ $? −eq $SUCCESS ]<br />

then<br />

echo "$word found in $filename"<br />

else<br />

echo "$word not found in $filename"<br />

fi<br />

Example 30−6 demonstrates how to use grep to search for a word pattern in a system logfile.<br />

Example 12−12. Emulating "grep" in a script<br />

Chapter 12. External Filters, Programs and Commands 167

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

Saved successfully!

Ooh no, something went wrong!