Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash printf multiple lines from arg in columns

Tags:

bash

printf

I've been fiddling around with this for hours but can't get it to work, so maybe my approach is wrong.

I want to pretty-display multiple lines of a message, so the 'title' is to the left, and then the message aligns to that in a column, so for example, like:

WARNING: The quick brown fox jumped over the lazy dog.
         Sphinx of black quartz, judge my vow.
         How quickly daft jumping zebras vex!

or

NOTE: This happened.
      Foo bar.

and so on.

I'm trying to do this with printf and column based on some answers I could find, but as I say, maybe this approach can never work?

At the moment, I have the first string for printf as the 'title' and then the rest of the args are the message to align to that, like so:

#!/bin/bash

warn() {
  printf '%s+%s\n' 'WARNING:' "${@}" | column --table --separator '+'
}

warn "The quick brown fox jumped over the lazy dog." \
     "+Sphinx of black quartz, judge my vow." \
     "+How quickly daft jumping zebras vex!"

Can this be done similarly? Or what is the best way/some other way to do this?

Actual output:

WARNING:  The quick brown fox jumped over the lazy dog.    
          Sphinx of black quartz, judge my vow.            How quickly daft jumping zebras vex!
like image 775
algalg Avatar asked Oct 12 '25 12:10

algalg


1 Answers

Here is an implementation that requires no loop and no sub shell:

#!/usr/bin/env bash

taggedMessage() {
  # Prints first message with prepend tag
  printf '%s %s\n' "${1:?}" "${2:?}"

  [ $# -gt 2 ] || return # Returns if only one message

  # Constructs blank filler of same length as tag
  printf -v filler '%*s' ${#1} ''

  shift 2 # Shifts arguments at 2nd message

  # Prints remaining messages with prepend filler
  printf %s\\n "${@/#/$filler }"
}

warn() { taggedMessage 'WARNING:' "$@";}

warn "The quick brown fox jumped over the lazy dog." \
     "Sphinx of black quartz, judge my vow." \
     "How quickly daft jumping zebras vex!"

taggedMessage 'SINGLE:' 'A single-line message.'

taggedMessage 'RANDOM TAG:' \
    "The quick brown fox jumped over the lazy dog." \
    "Sphinx of black quartz, judge my vow." \
    "How quickly daft jumping zebras vex!"
like image 111
Léa Gris Avatar answered Oct 14 '25 23:10

Léa Gris