© jirkaejc, 123RF.com
Script utilities in depth: grep, awk, and sed
Players
A variety of scripts rely on common Linux commands as well as Bash scripting features to accomplish their tasks. For example, the code example in Listing 1 displays the current date and time in a specified city.
Listing 1
Display Date and Time
01 if [ "$1" = "" ]; then 02 echo "City name required." 03 exit 04 fi 05 city=`echo $1 | sed -e 's/ /_/g'` 06 z=`find /usr/share/zoneinfo -type f | \ 07 grep -v 'posix|right|Etc|SystemV | \ 08 grep -i $city` 09 echo -n "Time in $1: "; TZ=`echo $z` date
The first section of this code ensures that the script's argument was not omitted using an if statement. The next command defines the variable city as the script's first argument, transformed so that spaces are replaced by underscores via sed. Next, the variable z is constructed from a sequence of three commands: the find command locates all time zone definition files, the first grep command removes some unwanted entries from that list, and the final grep extracts the entry corresponding to the specified city.
The final command displays the desired information in an attractive format. This small snippet illustrates the way Bash control structures and commands like grep can be combined to perform a specific job. Here, grep operates as a tool that extracts the desired portions from some larger block of information, providing utility and functionality to the Bash scripting environment (analogous to a utility infielder in baseball).
In this column, I'll take a closer, more detailed look at three of these important tools, which are useful both at the command line and within scripts:
...Buy this article as PDF
(incl. VAT)
Buy ADMIN Magazine
Subscribe to our ADMIN Newsletters
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Most Popular
Support Our Work
ADMIN content is made possible with support from readers like you. Please consider contributing when you've found an article to be beneficial.

