How can I align the columns of tables in Bash?

前端 未结 9 2030
一个人的身影
一个人的身影 2020-12-02 08:25

I\'d like to output a table format text. What I tried to do was echo the elements of an array with \'\\t\', but it was misaligned.

My code

for((i=0;i         


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 08:45

    awk solution that deals with stdin

    Since column is not POSIX, maybe this is:

    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 [ "$1" = - ]; then
        rm "$file"
      fi
    )
    

    Test:

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

    Test commands:

    mycolumn file
    mycolumn 

    Output for all:

          12   1234      1
    12345678      1    123
        1234 123456 123456
    

    See also:

    • Using awk to align columns in text file?
    • AWK: go through the file twice, doing different tasks

提交回复
热议问题