Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right text align - bash

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

like image 608
cubrilo Avatar asked Nov 21 '10 16:11

cubrilo


3 Answers

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
like image 111
icyrock.com Avatar answered Nov 10 '22 23:11

icyrock.com


Your final step could be

sed -e :a -e 's/^.\{1,$length\}$/ &/;ta'
like image 43
Wesley Rice Avatar answered Nov 11 '22 00:11

Wesley Rice


This is a very old question (2010) but it's the top google result, so might as well. Of the existing answers here, one is a guess that doesn't adjust for terminal width, and the other one invokes sed which is unnecessarily costly.

The printf solution is better as it's a bash builtin, so it vwon't slow things down, but instead of guessing - bash gives you $COLUMNS to tell you how wide the terminal window you're dealing with is.

so while you can explicitly align to, say the 40th column:

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

You can size it for whatever your terminal width is with:

printf "%$COLUMNSs\n" "$the_weather"

(since we're mixing up syntax here, we have used the full form syntax for a bash variable i.e. ${COLUMNS} instead of $COLUMNS, so that bash can identify the variable from the other syntax

In action .. now that we've freed up all that sed processing time, we can use it for something else maybe:

the_weather="$(curl -sm2 'http://wttr.in/Dublin?format=%l:+%c+%f')"
printf "%${COLUMNS}s\n" "${the_weather:-I hope the weather is nice}"
like image 1
Tadhg Avatar answered Nov 10 '22 23:11

Tadhg