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.

#!/bin/bash<br />

# grp.sh: Very crude reimplementation of 'grep'.<br />

E_BADARGS=65<br />

if [ −z "$1" ] # Check for argument to script.<br />

then<br />

echo "Usage: `basename $0` pattern"<br />

exit $E_BADARGS<br />

fi<br />

echo<br />

for file in * # Traverse all files in $PWD.<br />

do<br />

output=$(sed −n /"$1"/p $file) # Command substitution.<br />

if [ ! −z "$output" ]<br />

# What happens if "$output" is not quoted?<br />

then<br />

echo −n "$file: "<br />

echo $output<br />

fi<br />

# sed −ne "/$1/s|^|${file}: |p" is equivalent to above.<br />

echo<br />

done<br />

echo<br />

exit 0<br />

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

# Exercises:<br />

# −−−−−−−−−<br />

# 1) Add newlines to output, if more than one match in any given file.<br />

# 2) Add features.<br />

egrep is the same as grep −E. This uses a somewhat different, extended set of regular<br />

expressions, which can make the search somewhat more flexible.<br />

fgrep is the same as grep −F. It does a literal string search (no regular expressions),<br />

which allegedly speeds things up a bit.<br />

agrep extends the capabilities of grep to approximate matching. The search string<br />

may differ by a specified number of characters from the resulting matches. This utility<br />

is not part of the core Linux distribution.<br />

To search compressed files, use zgrep, zegrep, or zfgrep. These also work on<br />

non−compressed files, though slower than plain grep, egrep, fgrep. They are handy<br />

for searching through a mixed set of files, some compressed, some not.<br />

look<br />

To search bzipped files, use bzgrep.<br />

The command look works like grep, but does a lookup on a "dictionary", a sorted word list. By<br />

default, look searches for a match in /usr/dict/words, but a different dictionary file may be<br />

specified.<br />

Chapter 12. External Filters, Programs and Commands 168

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

Saved successfully!

Ooh no, something went wrong!