Come allineare le colonne nell'output da un comando UNIX?


21

Conoscevo un comando - un vero comando, attenzione, non sed / awk magic - che formattava il suo input per essere allineato in colonne. Ad esempio, se hai eseguito:

% echo -e "aaaaa bbbbbbb\ncc ddd"
aaaaa bbbbbbb
cc ddd

Ma se hai eseguito l'output tramite il comando di cui ho dimenticato il nome:

% echo -e "aaaaa bbbbbbb\ncc ddd" | mystery_command
aaaaa    bbbbbbb
cc       ddd

Qualcuno conosce il nome di quel comando?

Risposte:



0

awk soluzione che si occupa di stdin

Poiché columnnon è POSIX, forse questo è:

mycolumn() (
  file="${1:--}"
  if [ "$file" = - ]; then
    file="$(mktemp)"
    cat >"${file}"
  fi
  awk '
  FNR == 1 { if (NR == FNR) next }
  NR == FNR {
    for (i = 1; i <= NF; i++) {
      l = length($i)
      if (w[i] < l)
        w[i] = l
    }
    next
  }
  {
    for (i = 1; i <= NF; i++)
      printf "%*s", w[i] + (i > 1 ? 1 : 0), $i
    print ""
  }
  ' "$file" "$file"
  if [ "$file" = - ]; then
    rm "$file"
  fi
)

Test:

printf '12 1234 1
12345678 1 123
1234 123456 123456
' > file

Comandi di test:

mycolumn file
mycolumn <file
mycolumn - <file

Uscita per tutti:

      12   1234      1
12345678      1    123
    1234 123456 123456

Guarda anche:

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.