Home > Blockchain >  Bash: How to dynamically pad spaces as per the max column size
Bash: How to dynamically pad spaces as per the max column size

Time:12-14

Below will be output from bash script. I have more than 10 columns and don't want to waste space. I am dynamically calculating the max length of entries in every column and storing it. Now I want to use this max length for dynamically pad spaces to each column.

|No.           |IPAddress     |Link Speed        
|1             |20.0.2.134    |4.0           
|2             |20.0.2.136    |1.0           

code:

# Collect the max size of each column and stored in col_length
declare -a col_length
for (( col=1; col<=$(head -n1 $tmp_file | awk -F '::' '{print NF}'); col   ));
do
    length=$(get_column_size "$col")
    col_length =($col $length)
done

#Print with formatting
cat $tmp_file | while read line 
do
   echo $line | awk -F'::' '{
    for(i=1;i<=NF;i  ){
        printf "|%-14s", $i}; 
    }'
   printf "\n"
done

Currently I am using %-14s, but I want it to be dynamically provided. For e.g., for first column, I don't need 14 space padding.

CodePudding user response:

You could do all this with just one awk invocation:

awk -F '::' 'NR==1 {for(i=1; i<=NF; i  ) len[i]=length($i)}
  {for(i=1; i<=NF; i  ) printf "|%-" len[i] "s", $i; printf "\n"}' "$tmp_file"

Note that GNU awk supports the * format modifier:

awk -F '::' 'NR==1 {for(i=1; i<=NF; i  ) len[i]=length($i)}
  {for(i=1; i<=NF; i  ) printf "|%-*s", len[i], $i; printf "\n"}' "$tmp_file"

CodePudding user response:

If you can live without the pipe symbols in the output:

sed -E 's/  //g' $tmp.file | column -s '|' -t 
No.  IPAddress   LinkSpeed
1    20.0.2.134  4.0
2    20.0.2.136  1.0
  • Related