Some text on the left, some text on the right, on a single line, with BASH

Go To StackoverFlow.com

0

I have some status text displayed in a BASH script, e.g.:

Removed file "sandwich.txt". (1/2)
Removed file "fish.txt". (2/2)

I would like to have the progress text (1/2) appear entirely to the right, lined up with the edge of the terminal window, e.g.:

Removed file "sandwich.txt".                           (1/2)
Removed file "fish.txt".                               (2/2)

I have tried solutions at right align/pad numbers in bash and right text align - bash, however, the solutions do no seem to work, they just make a large white space, e.g.:

Removed file "sandwich.txt".                           (1/2)
Removed file "fish.txt".                           (2/2)

How can I have some of the text left aligned and some of the text right aligned?

2012-04-04 02:16
by Village
"the second solution does not always keep the right column lined up with the right edge of the terminal" is why the first solution is so complex - Ignacio Vazquez-Abrams 2012-04-04 02:17
possible duplicate of right align/pad numbers in bashIgnacio Vazquez-Abrams 2012-04-04 02:33
Not a duplicate; this question is about right-aligning with the edge of the terminal, not just how to use printf - ghoti 2012-04-04 03:19


4

printf "Removed file %-64s (%d/%d)\n" "\"$file\"" $n $of

The double quotes around the file name are eclectic, but get the file name enclosed in double quotes to the printf() command, which will then print that name left justified in a field of width 64.

Adjust to suit.

$ file=sandwich.txt; n=1; of=2
$ printf "Removed file %-64s (%d/%d)\n" "\"$file\"" $n $of
Removed file "sandwich.txt"                                                   (1/2)
$
2012-04-04 02:53
by Jonathan Leffler


3

This will automatically adjust to your terminal width, whatever that is.

[ghoti@pc ~]$ cat input.txt 
Removed file "sandwich.txt". (1/2)
Removed file "fish.txt". (2/2)
[ghoti@pc ~]$ cat doit
#!/usr/bin/awk -f

BEGIN {
  "stty size" | getline line;
  split(line, stty);
  fmt="%-" stty[2]-9 "s%8s\n";
  print "term width = " stty[2];
}

{
  last=$NF;
  $NF="";
  printf(fmt, $0, last);
}

[ghoti@pc ~]$ ./doit input.txt 
term width = 70
Removed file "sandwich.txt".                                    (1/2)
Removed file "fish.txt".                                        (2/2)
[ghoti@pc ~]$ 

You can remove the print in the BEGIN block; that was just there to show the width.

To use this, basically just pipe any existing status line creation through the awk script, and it'll move the last field to the right side of the terminal.

2012-04-04 03:13
by ghoti