right text align - bash

cubrilo picture cubrilo · Nov 21, 2010 · Viewed 20.2k times · Source

I have one problem. My text should be aligned by right in specified width. I have managed to cut output to the desired size, but i have problem with putting everything on right side

Here is what i got:

#!/usr/local/bin/bash

length=$1
file=$2
echo $1

echo -e "length = $length \t  file = $file "
f=`fold -w$length $file > output`
while read line
do
        echo "line is $line"
done < "output"

thanks

Answer

icyrock.com picture icyrock.com · Nov 21, 2010

Try:

printf "%40.40s\n" "$line"

This will make it right-aligned with width 40. If you want no truncation, drop .40 (thanks Dennis!):

printf "%40s\n" "$line"

For example:

printf "%5.5s\n" abc
printf "%5.5s\n" abcdefghij
printf "%5s\n" abc
printf "%5s\n" abcdefghij

will print:

  abc
abcde
  abc
abcdefghij