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...

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

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

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

#!/bin/bash<br />

# wstrings.sh: "word−strings" (enhanced "strings" command)<br />

#<br />

# This script filters the output of "strings" by checking it<br />

#+ against a standard word list file.<br />

# This effectively eliminates all the gibberish and noise,<br />

#+ and outputs only recognized words.<br />

# =================================================================<br />

# Standard Check for Script Argument(s)<br />

ARGS=1<br />

E_BADARGS=65<br />

E_NOFILE=66<br />

if [ $# −ne $ARGS ]<br />

then<br />

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

exit $E_BADARGS<br />

fi<br />

if [ −f "$1" ]<br />

# Check if file exists.<br />

then<br />

file_name=$1<br />

else<br />

echo "File \"$1\" does not exist."<br />

exit $E_NOFILE<br />

fi<br />

# =================================================================<br />

MINSTRLEN=3<br />

# Minimum string length.<br />

WORDFILE=/usr/share/dict/linux.words # Dictionary file.<br />

# May specify a different<br />

#+ word list file<br />

#+ of format 1 word per line.<br />

wlist=`strings "$1" | tr A−Z a−z | tr '[:space:]' Z | \<br />

tr −cs '[:alpha:]' Z | tr −s '\173−\377' Z | tr Z ' '`<br />

# Translate output of 'strings' command with multiple passes of 'tr'.<br />

# "tr A−Z a−z" converts to lowercase.<br />

# "tr '[:space:]'" converts whitespace characters to Z's.<br />

# "tr −cs '[:alpha:]' Z" converts non−alphabetic characters to Z's,<br />

#+ and squeezes multiple consecutive Z's.<br />

# "tr −s '\173−\377' Z" converts all characters past 'z' to Z's<br />

#+ and squeezes multiple consecutive Z's,<br />

#+ which gets rid of all the weird characters that the previous<br />

#+ translation failed to deal with.<br />

# Finally, "tr Z ' '" converts all those Z's to whitespace,<br />

#+ which will be seen as word separators in the loop below.<br />

# Note the technique of feeding the output of 'tr' back to itself,<br />

#+ but with different arguments and/or options on each pass.<br />

for word in $wlist<br />

do<br />

# Important:<br />

# $wlist must not be quoted here.<br />

# "$wlist" does not work.<br />

# Why?<br />

Chapter 12. External Filters, Programs and Commands 183

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

Saved successfully!

Ooh no, something went wrong!