A long time ago I remember using a command that makes its input into a nicely formatted table.
For example, for this input,
apple 1 100 orange 20 19 pineapple 1000 87 avocado 4 30
The output will be similar to this:
apple 1 100 orange 20 19 pineapple 1000 87 avocado 4 30
I’d like to know the name of this tool.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use column -t. column is part of util-linux.
$ column -t <<END > apple 1 100 > orange 20 19 > pineapple 1000 87 > avocado 4 30 > END apple 1 100 orange 20 19 pineapple 1000 87 avocado 4 30
Method 2
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:
- https://stackoverflow.com/questions/14095011/using-awk-to-align-columns-in-text-file
- https://stackoverflow.com/questions/28544105/awk-go-through-the-file-twice-doing-different-tasks
Method 3
For relatively small files, (where the length in bytes is less than getconf ARG_MAX), and the input sizes are more or less known, (let’s say no fruit name is more than 18 letters long), printf can be useful, here’s a bash example:
printf '%-20s %5s %5sn' $(<file.txt)
Output:
apple 1 100 orange 20 19 pineapple 1000 87 avocado 4 30
Note how the numbers are right justified.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0