【发布时间】:2011-01-13 01:53:27
【问题描述】:
我正在尝试对脚本中的输出数据进行一些格式化,而不是确定如何进行左右对齐以及宽度。谁能指出我正确的方向?
【问题讨论】:
标签: shell scripting width sh justify
我正在尝试对脚本中的输出数据进行一些格式化,而不是确定如何进行左右对齐以及宽度。谁能指出我正确的方向?
【问题讨论】:
标签: shell scripting width sh justify
Here 是一个执行完全对齐和断字的 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";
【讨论】:
你可以使用纯 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"
【讨论】:
sh 是 Bourne Shell。 Bash 是 ... Bourne 再次 Shell。
你可以使用 printf。例子
$ printf "%15s" "col1"
$ printf "%-15s%-15s" "col1" "col2"
awk 等工具也具有格式化功能
$ echo "col1 col2" | awk '{printf "%15s%15s\n", $1,$2}'
col1 col2
【讨论】:
通过fmt 传递它?实际上并不是特定于 bourne shell,但仍然...
【讨论】:
左对齐有点简单,要获得右对齐,您可以像这样使用printf 和环境变量$COLUMNS:
printf "%${COLUMNS}s" "your right aligned string here"
【讨论】:
你不是很清楚,但最简单的方法可能是只使用@987654321@(shell命令,而不是同名的C函数)。
【讨论】: