Download Unix Shell Programming is a tutorial aimed at helping Unix and
Transcript
The following program, called number, is a simplified version of the standard Unix nl command: It takes one or more files given as arguments and displays them preceded by line numbers. If no arguments are supplied, it uses standard input instead. $ cat number # # Number lines from files given as argument or from # standard input if none supplied # lineno=1 cat $* | while read line do echo "$lineno: $line" lineno=$((lineno + 1)) done $ The variable lineno—the line number count—is initially set to 1. Then the arguments typed to number are given to cat to be collectively written to standard output. If no arguments are supplied, $* will be null, and cat will be passed no arguments. This will cause it to read from standard input. The output from cat is piped into the while loop. For each line read by read, the line is echoed at the terminal, preceded by the value of lineno, whose value is then incremented by one. $ number phonebook 1: Alice Chebba 973-555-2015 2: Barbara Swingle 201-555-9257 3: Billy Bach 201-555-7618 4: El Coyote 212-555-3232