Hour 16

1: Using sed, write a shell function that searches for a word or simple expression in a list of files, printing out a list of matches.

You do not have to support all possible sed expressions. Your function should take the word to look for as its first argument. It should treat its other arguments as a list of files.

HINT: Use double quotes (") instead of single quotes (') to surround your sed script.

A1: One possible implementation is
sgrep() {
    if [ $# -lt 2 ] ; then
        echo "USAGE: sgrep pattern files" >&2
        exit 1
    fi

    PAT="$1" ; shift ;

    for i in $@ ;
    do
        if [ -f "$i" ] ; then
            sed -n "/$PAT/p" $i
        else
            echo "ERROR: $i not a file." >&2
        fi
    done

    return 0
}
2: Write a sed command that takes as its input the output of the uptime command and prints ...

Get Sams Teach Yourself Shell Programming in 24 Hours, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.