Bash command or tool to align columns

Hi,

I was wondering if there is any tool or version of a command with in awk itself which I can use to align text in a file. For example, the content of my file is something like as follows.

allocated_disk_in_TB	consumed_in_TB	free_in_TB
24.1934	10.3604	13.8496
allocated_disk_in_TB	consumed_in_TB	free_in_TB
23.1436	8.5918	14.5664
allocated_disk_in_TB	consumed_in_TB	free_in_TB
47.3369	18.9521	28.4160

I would like to align starting point of each column sequentially in a line at the same spot where the columns started in the line above.

I would like to transform the content above to as follows.

allocated_disk_in_TB	consumed_in_TB	free_in_TB
24.1934	                        10.3604	                13.8496
allocated_disk_in_TB	consumed_in_TB	free_in_TB
23.1436	                        8.5918	                14.5664
allocated_disk_in_TB	consumed_in_TB	free_in_TB
47.3369	                        18.9521	                28.4160

Thanks,
Sajan Gone

@sajangone , welcome, how are they different ?

when you say 'something like ... ', why not show that 'something' ?

NB: use the markdown menu options to format your text

I have edited your post and put ``` lines around the code sections.

1 Like

It's tab-separated.
The tab expansion in a terminal usually makes fields that are 8 characters long. Because the field values are longer, the output seems not aligned.
You can try

expand -t30,50,70 filename

Or use printf, in awk

awk -F'\t' '{ printf "%-30s %-20s %-20s\n", $1, $2, $3 }' filename

in bash

while IFS=$'\t' read -r f1 f2 f3
do
  printf "%-30s %-20s %-20s\n" "$f1" "$f2" "$f3"
done < filename

This would calculate the lengths (instead of relying on fixed numbers):

$ declare -f prettify 
prettify () 
{ 
    read -r col1h col2h col3h < <(grep -m1 '^allocated' "$1");
    while read -r col1 col2 col3; do
        printf "%-${#col1h}s\t%-${#col2h}s\t%s\n" "${col1}" "${col2}" "${col3}";
    done < "$1"
}
$ cat input.txt 
allocated_disk_in_TB	consumed_in_TB	free_in_TB
24.1934	10.3604	13.8496
allocated_disk_in_TB	consumed_in_TB	free_in_TB
23.1436	8.5918	14.5664
allocated_disk_in_TB	consumed_in_TB	free_in_TB
47.3369	18.9521	28.4160
$ prettify input.txt
allocated_disk_in_TB	consumed_in_TB	free_in_TB
24.1934             	10.3604       	13.8496
allocated_disk_in_TB	consumed_in_TB	free_in_TB
23.1436             	8.5918        	14.5664
allocated_disk_in_TB	consumed_in_TB	free_in_TB
47.3369             	18.9521       	28.4160

Hinted by: scripting - Bash shell script output alignment - Unix & Linux Stack Exchange

Ah yes, the hinted article mentions the "automatic" column command:

column -t -s $'\t' filename

BTW the shell function can be optimized:

prettify () 
{
    header=1
    while IFS=$'\t' read -r col1 col2 col3; do
        [[ $header ]] && header= w1=${#col1} w2=${#col2}
        printf "%-${w1}s\t%-${w2}s\t%s\n" "${col1}" "${col2}" "${col3}"
    done < "$1"
}

It assumes that the first line is the header.

2 Likes