sed and awk

Transforming text on the command line: sed's substitution and addresses, awk's fields, patterns, BEGIN, END and totals.

  • 29 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • sed: what is it?

    Show the answer

    A stream editor that reads a text line by line, applies commands to each one (substitute, delete, print) and writes the result to its output.

    It does not modify the file it reads: without -i, the result goes to standard output. The most common command is s/pattern/replacement/.

  • What does this command print?

    ```bash
    echo 'a-b-c' | sed 's/-/+/2'
    `

    • a-b+c
    • a+b-c
    • a+b+c
    • a-b-c+
    Show the answer

    a-b+c

    The number at the end of s names the occurrence to replace: the second dash becomes +, the first stays. With no number it is the first; with g, all of them.

  • In sed, the s/a/b/ command replaces only the first occurrence on each line; to replace them all, add the … flag.

    Show the answer

    In sed, the s/a/b/ command replaces only the first occurrence on each line; to replace them all, add the g flag.

    echo a-b-c | sed 's/-/+/' gives a+b-c and with g a+b+c. A number instead, as in s/-/+/2, targets the second occurrence: a-b+c.

  • awk: what is it?

    Show the answer

    A text-processing language that splits each line into fields and runs an action on those that match a pattern.

    A program is a series of pattern { action }. With no pattern, the action applies to every line; with no action, the line is printed.

  • The replacement sed 's/usr/sbin/bin/' paths.txt fails with “unknown option to s”. Which fix is right?

    • sed 's#usr/sbin#bin#' paths.txt
    • sed 's/usr/sbin/bin/g' paths.txt
    • sed -n 's/usr/sbin/bin/' paths.txt
    • sed 's/usr/sbin/' paths.txt
    Show the answer

    sed 's#usr/sbin#bin#' paths.txt

    The path's slashes are read as s separators: sed finds too many parts and takes bin/ for a flag. Change the separator, here #, or protect each slash with \. g and -n change nothing.