如何在UNIX命令的输出中对齐列?


21

我曾经知道一个命令-是您的实际命令,而不是sed / awk魔术-格式化了其输入以使其按列对齐。例如,如果您运行:

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

但是,如果您通过命令运行了输出,而我忘记了该命令的名称:

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

有人知道该命令的名称吗?

Answers:



0

awk 解决标准输入的解决方案

由于column不是POSIX,可能是:

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
)

测试:

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

测试命令:

mycolumn file
mycolumn <file
mycolumn - <file

全部输出:

      12   1234      1
12345678      1    123
    1234 123456 123456

也可以看看:

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.