Contributed by Tom Christiansen
Here's a sed script I use to extract a termcap entry. It works for any termcap-like file, such as disktab. For example:
$gent vt100
extracts the vt100 entry from termcap, while:
$gent eagle /etc/disktab
gets the eagle entry from disktab. Now I know it could have been done in C or Perl, but I did it a long time ago. It's also interesting because of the way it passes options into the sed script. I know, I know: it should have been written in sh not csh, too.
#!/bin/csh -f set argc = $#argv set noglob set dollar = '$' set squeeze = 0 set noback="" nospace="" rescan: if ( $argc > 0 && $argc < 3 ) then if ( "$1" =~ -* ) then if ( "-squeeze" =~ $1* ) then set noback='s/\\//g' nospace='s/^[ ]*//' set squeeze = 1 shift @ argc -- goto rescan else echo "Bad switch: $1" goto usage endif endif set entry = "$1" if ( $argc == 1 ) then set file = /etc/termcap else set file = "$2" endif else usage: echo "usage: `basename $0` [-squeeze] entry [termcapfile]" exit 1 endif sed -n -e \ "/^${entry}[|:]/ {\ :x\ /\\${dollar}/ {\ ${noback}\ ${nospace}\ p\ n\ bx\ }\ ${nospace}\ p\ n\ /^ / {\ bx\ }\ }\ /^[^ ]*|${entry}[|:]/ {\ :y\ /\\${dollar}/ {\ ${noback}\ ${nospace}\ p\ n\ by\ }\ ${nospace}\ p\ n\ /^ / {\ by\ }\ }" < $file
Once you get used to reading awk scripts, they seem so much easier to understand than all but the simplest sed script. It can be a painstaking task to figure out what a small sed script like the one shown here is doing.
This script does show how to pass shell variables into a sed script. Variables are used to pass optional sed commands into the script, such as the substitution commands that replace backslashes and spaces.
This script could be simplified in several ways. First of all, the two regular expressions don't seem necessary to match the entry. The first matches the name of the entry at the beginning of a line; the second matches it elsewhere on the line. The loops labeled x and y are identical and even if the two regular expressions were necessary, we could have them branch to the same loop.