0

我在 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)

我已经在 bash和右文本 align - bash中尝试了右对齐/填充数字的解决方案,但是,这些解决方案似乎不起作用,它们只是产生了一个很大的空白,例如:

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

我怎样才能让一些文本左对齐而一些文本右对齐?

4

2 回答 2

4
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)
$
于 2012-04-04T02:53:33.877 回答
3

这将自动调整到您的终端宽度,无论是什么。

[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 ~]$ 

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

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

于 2012-04-04T03:13:38.580 回答