2

我正在尝试对脚本中的输出数据进行一些格式化,而不是肯定如何做左右对齐以及宽度。谁能指出我正确的方向?

4

6 回答 6

4

you can use printf. examples

$ printf "%15s" "col1"
$ printf "%-15s%-15s" "col1" "col2"

tools like awk also has formatting capabilities

$ echo "col1 col2" | awk '{printf "%15s%15s\n", $1,$2}'
           col1           col2
于 2010-02-04T13:41:14.867 回答
1

你不是很清楚,但最简单的方法可能是只使用printf()(shell命令,而不是同名的C函数)。

于 2010-02-04T13:10:34.767 回答
1

您可以使用纯 bash 来完成:

x="Some test text"
width="                    "      # 20 blanks
echo "${width:0:${#width}-${#x}}$x"

输出是:

'      Some test text'             (obviously without the quotes)

所以你需要知道的两件事是 ${#var} 将获取 var 中字符串的长度,并且 ${var:x:y} 从 x 到 y 位置提取字符串。

您可能需要最新版本(在 GNU bash 3.2.25 上测试)

编辑:想想看,你可以这样做:

echo "${width:${#x}}$x"
于 2010-02-04T13:59:57.507 回答
0

Left align is kind of trivial, to get right align you can use printf and the envrironment variable $COLUMNS like that:

 printf "%${COLUMNS}s" "your right aligned string here"
于 2010-02-04T13:40:48.073 回答
0

Pipe it through fmt? Not actually bourne shell specific, but still...

于 2010-02-04T13:45:09.257 回答
0

是一个执行完全对齐和断字的 Perl 脚本。

这是向该脚本添加左边距功能的差异:

--- paradj.pl   2003-11-17 09:45:21.000000000 -0600
+++ paradj.pl.NEW       2010-02-04 09:14:09.000000000 -0600
@@ -9,16 +9,18 @@
 use TeX::Hyphen;

 my ($width, $hyphenate, $left, $centered, $right, $both);
-my ($indent, $newline);
+my ($indent, $margin, $newline);
 GetOptions("width=i" => \$width, "help" => \$hyphenate,
   "left" => \$left, "centered" => \$centered,
   "right" => \$right, "both" => \$both,
+  "margin:i" => \$margin,
   "indent:i" => \$indent, "newline" => \$newline);

 my $hyp = new TeX::Hyphen;

 syntax() if (!$width);
 $indent = 0 if (!$indent);
+$margin = 0 if (!$margin);

 local $/ = "";

@@ -147,6 +149,7 @@
       }
     }

+    print " " x $margin;
     print "$lineout\n";
   }
 }
@@ -185,6 +188,9 @@
   print "initial\n";
   print "                                indention (defaults ";
   print "to 0)\n";
+  print "--margin=n (or -m=n or -m n)  Add a left margin of n ";
+  print "spaces\n";
+  print "                                (defaults to 0)\n";
   print "--newline (or -n)             Output an empty line \n";
   print "                                between ";
   print "paragraphs\n";
于 2010-02-04T14:51:23.817 回答