Исправлена ​​ошибка печати пространства / ширины переменных в оболочке

860
Bimal Poudel

Я сделал табличный отчет о некоторых переменных данных, напечатанных через printf в оболочке.

Project One | 76 | 80M | 80M | 80M  Project Two | 46M | 52M | 52M | 52M  Project Three | 174 | 171M | - | 173M  

Выходные данные здесь вручную. Есть ли способ печати переменных, которые занимают фиксированную ширину?

Например, в первом ряду 76 [пробел], 80M, ... всего три символа ширины с печатью с переменной оболочки.

0

1 ответ на вопрос

0
theoden

If I understood what you want is a function to leave certain number of spaces after a specified string. Here it is:

fix_space() { string="$1" len="$2" perl -e "my \$str = '`printf "$string" | sed "s/'/\\'/g"`'; print \$str.' ' x ($len - length(\$str))" } echo "'`fix_space "ololfdsaf" 20`'" echo "'`fix_space "ololff" 20`'" 

It simply makes perl doing all the dirty job. String goes as the first argument, and the full length as the second. I am sure this will help you to align your output.

EDIT:

You can do it without perl with only using shell. Then you have to type:

printf "'$string`printf ' '%.0s ))}`'\n" 

Reference

http://rosettacode.org/wiki/Repeat_a_string#UNIX_Shell

Давайте не будем называть эту жемчужину грязной работой; потому что это работает сейчас, как я хотел. Я буду использовать это. Благодарю. Bimal Poudel 8 лет назад 0
@BimalPoudel, I extended the answer in case you bother time consumption. Using printf is a faster. theoden 8 лет назад 0

Похожие вопросы