Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash & Printf: How can I both right pad and truncate?

In Bash ...

I know how to right pad with printf

printf "%-10s" "potato"

I know how to truncate with printf

printf "%.10s" "potatos are my best friends"

How can I do both at the same time?

LIST="aaa bbbbb ccc ddddd"
for ITEM in $LIST; do
  printf "%-.4s blah" $ITEM
done

This prints

aaa blah
bbbbb blah
ccc blah
ddddd blah

I want it to print

aaa  blah
bbbb blah
ccc  blah
dddd blah

I'd rather not do something like this (unless there's no other option):

LIST="aaa bbbbb ccc ddddd"
for ITEM in $LIST; do
  printf "%-4s blah" $(printf "%.4s" "$ITEM")
done

though, obviously, that works (it feels ugly and hackish).

like image 303
Sir Robert Avatar asked Oct 26 '25 02:10

Sir Robert


1 Answers

You can use printf "%-4.4s for getting both formatting in output:

for ITEM in $LIST; do printf "%-4.4s blah\n" "$ITEM"; done
aaa  blah
bbbb blah
ccc  blah
dddd blah
like image 99
anubhava Avatar answered Oct 29 '25 07:10

anubhava