2012-04-04 27 views
0

我有一個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://stackoverflow.com/questions/994461/right-align-pad-numbers-in-bash) – 2012-04-04 02:33:20

+0

不是重複;這個問題是關於與終端邊緣對齊的,而不僅僅是如何使用printf。 – ghoti 2012-04-04 03:19:10

回答

3
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) 
$ 
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腳本管道創建任何現有的狀態行,它會將最後一個字段移到終端的右側。

相關問題