Adding a Prefix or Suffix to Output

Problem

You’d like to add a prefix or a suffix to each line of output from a given command for some reason. For example, you’re collecting last statistics from many machines and it’s much easier to grep or otherwise parse the data you collect if each line contains the hostname.

Solution

Pipe the appropriate data into a while read loop and printf as needed. For example, this prints the $HOSTNAME, followed by a tab, followed by any nonblank lines of out-put from the last command:

$ last | while read i; do [[ -n "$i" ]] && printf "%b" "$HOSTNAME\t$i\n"; done

# Write a new logfile
$ last | while read i; do [[ -n "$i" ]] && printf "%b" "$HOSTNAME\t$i\n"; done >
last_$HOSTNAME.log

Or you can use awk to add text to each line:

$ last | awk "BEGIN { OFS=\"\t\" } ! /^\$/ { print \"$HOSTNAME\", \$0}"

$ last | awk "BEGIN { OFS=\"\t\" } ! /^\$/ { print \"$HOSTNAME\", \$0}" \
    > last_$HOSTNAME.log

Discussion

We use [[ -n "$i" ]] to remove any blank lines from the last output, and then we use printf to display the data. Quoting for this method is simpler, but it uses more steps (last, while, and read, as opposed to just last and awk). You may find one method easier to remember, more readable, or faster than the other, depending on your needs.

There is a trick to the awk command we used here. Often you will see single quotes surrounding awk commands to prevent the shell from interpreting awk variables as shell variables. However in this case we want the shell to interpolate ...

Get bash Cookbook 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.