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

# Exercises:<br />

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

# 1) Add 'sed' commands to filter out other punctuation, such as commas.<br />

# 2) Modify to also filter out multiple spaces and other whitespace.<br />

# 3) Add a secondary sort key, so that instances of equal occurrence<br />

#+ are sorted alphabetically.<br />

exit 0<br />

bash$ cat testfile<br />

This line occurs only once.<br />

This line occurs twice.<br />

This line occurs twice.<br />

This line occurs three times.<br />

This line occurs three times.<br />

This line occurs three times.<br />

bash$ ./wf.sh testfile<br />

6 this<br />

6 occurs<br />

6 line<br />

3 times<br />

3 three<br />

2 twice<br />

1 only<br />

1 once<br />

expand, unexpand<br />

The expand filter converts tabs to spaces. It is often used in a pipe.<br />

cut<br />

The unexpand filter converts spaces to tabs. This reverses the effect of expand.<br />

A tool for extracting fields from files. It is similar to the print $N command set in awk, but more<br />

limited. It may be simpler to use cut in a script than awk. Particularly important are the −d (delimiter)<br />

and −f (field specifier) options.<br />

Using cut to obtain a listing of the mounted filesystems:<br />

cat /etc/mtab | cut −d ' ' −f1,2<br />

Using cut to list the OS and kernel version:<br />

uname −a | cut −d" " −f1,3,11,12<br />

Using cut to extract message headers from an e−mail folder:<br />

bash$ grep '^Subject:' read−messages | cut −c10−80<br />

Re: Linux suitable for mission−critical apps?<br />

MAKE MILLIONS WORKING AT HOME!!!<br />

Spam complaint<br />

Re: Spam complaint<br />

Using cut to parse a file:<br />

Chapter 12. External Filters, Programs and Commands 162

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

Saved successfully!

Ooh no, something went wrong!