上留下一些文字,右边一些文字,在一行上,用BASH

问题描述:

我有一个bash脚本显示某些状态的文本,如:上留下一些文字,右边一些文字,在一行上,用BASH

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

我想有进步文本(1/2)完全显示在右侧,一字排开与终端窗口的边缘,例如:

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

我在right align/pad numbers in bashright text align - bash试图解决方案,但方案仍没有似乎工作,只能做了一个大的白色空间,例如:

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

我该如何让一些文字左对齐,并将一些文字右对齐?

+2

“第二种解决方案并不总是将右列与终端右边缘对齐”,这就是为什么第一个解决方案如此复杂。 – 2012-04-04 02:17:52

+0

可能重复的[右对齐/填充数字在bash](http://*.com/questions/994461/right-align-pad-numbers-in-bash) – 2012-04-04 02:33:20

+0

不是重复;这个问题是关于与终端边缘对齐的,而不仅仅是如何使用printf。 – ghoti 2012-04-04 03:19:10

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

周围文件名中的双引号是不拘一格,但得到双引号括起来的printf()命令的文件名,然后将打印名左对齐在宽度64

场调整以适应。

$ file=sandwich.txt; n=1; of=2 
$ printf "Removed file %-64s (%d/%d)\n" "\"$file\"" $n $of 
Removed file "sandwich.txt"             (1/2) 
$ 

这会自动调整到您的终端宽度,不管是什么。

[[email protected] ~]$ cat input.txt 
Removed file "sandwich.txt". (1/2) 
Removed file "fish.txt". (2/2) 
[[email protected] ~]$ 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); 
} 

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

您可以删除BEGIN块中的print;那只是为了显示宽度。

要使用这个,基本上只需通过awk脚本管道创建任何现有的状态行,它会将最后一个字段移到终端的右侧。