# # Snippet: Add a prefix before each line, except the first one. # # This migjt be useful if you write the output of a # command to a logfile including a timestamp printed # before, but you want all lines to be indented to # match the length of the timestamp. # # # The message containing multiple lines. # msg="This is a message with multiple lines." # # Length of the timestamp # timestamp_length=$(date --iso-8601=seconds | tr -d "\n" | wc -c) # # The prefix for continued lines: Repeated spaces # We need 4 more spaces than $timestamp_length because # of the brackets and two spaces added to the timestamp. # # @see https://unix.stackexchange.com/questions/188658/writing-a-character-n-times-using-the-printf-command # line_prefix=$(yes " " | head -$((timestamp_length + 4)) | tr -d "\n") # # Print the timestamp # printf "[$(date --iso-8601=seconds)] " # # Prefix each line of $msg with $line_prefix, except for the first one. # # NOTE: The AWK script spans pver multiple lines for better readability. # echo "${msg}" | awk "{ if (NR >= 2) { print \"${line_prefix}\"$0; } else { print $0; } }" # # The same command as above, but in one line # echo "${msg}" | awk "{ if (NR >= 2) { print \"${line_prefix}\"$0; } else { print $0;} }"