The Computer Oracle

How to align columns in output from a UNIX command?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Switch On Looping

--

Chapters
00:00 How To Align Columns In Output From A Unix Command?
00:27 Accepted Answer Score 37
00:42 Answer 2 Score 3
01:23 Thank you

--

Full question
https://superuser.com/questions/183861/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#unix

#avk47



ACCEPTED ANSWER

Score 37


It's column. Try for example echo -e "aaaaa bbbbbbb\ncc ddd" | column -t.




ANSWER 2

Score 3


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

Test:

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

Test commands:

mycolumn file
mycolumn <file
mycolumn - <file

Output for all:

12 1234 1
12345678 1 123
1234 123456 123456

See also: