1

I have a bash script that prints the following results:

120,900
1160,001
80,730
600,165
6,310
1111,203

I would like to left pad that so the result will be:

 120,900
1160,001
  80,730
 600,165
   6,310
1111,203

I already use that line to keep just 3 numbers after the comma in the second column

awk '{ printf "\t" $1 "\t|\t" "%.3f\n", $2 }' MyFile.txt;

How can I accomplish this?

  • Please do not post pictures of text; just paste the text. – DopeGhoti May 9 '18 at 16:10
  • 1
    If you have that awk snippet in the script, you could probably add the right-alignment there, too, instead of doing it as a separate step in the shell. – ilkkachu May 9 '18 at 18:44
1

Use printf rather than echo:

$ cat 442817.sh
#!/bin/bash
numbers=(120,900 1160,001 80,730 600,165 6,310 1111,203)
for n in "${numbers[@]}"; do
  printf "%10s\n" "$n"
done
$ ./442817.sh
   120,900
  1160,001
    80,730
   600,165
     6,310
  1111,203
  • 1
    or replace complete for loop with printf "%8s\n" "${numbers[@]}" – Cyrus May 9 '18 at 18:13
  • Also viable; the main thrust was to demonstrate printf, as opposed to echo; I just wanted to "show my work" as it were. – DopeGhoti May 9 '18 at 18:14
0

Awk solution:

awk 'FNR == NR{ len = length; if (len > max_len) max_len = len; next }
     { printf "%" max_len "s\n", $0 }' file.txt file.txt

The output:

 120,900
1160,001
  80,730
 600,165
   6,310
1111,203

Or via GNU coreutils:

printf "%$(sort -nr file.txt | wc -L)s\n" $(cat file.txt)
0
$ column -t -s, file | sed 's/^\([0-9]*\)\( *\)/\2\1,/'
   120,900
  1160,001
    80,730
   600,165
     6,310
  1111,203

The column output will be

120   900
1160  001
80    730
600   165
6     310
1111  203

and the sed command just moves the spaces between the two columns to the start of the line and inserts the comma in their place.

If the initial extra two spaces are not wanted, use

$ column -t -s, file | sed -e 's/^\([0-9]*\)\( *\)/\2\1,/' -e 's/^  //'
 120,900
1160,001
  80,730
 600,165
   6,310
1111,203

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.