如何在 Unix shell 脚本中用空格填充字符串?

use*_*225 3 unix shell-script

我有看起来像这样的数据:

01234567
09876544
12345676
34576980
Run Code Online (Sandbox Code Playgroud)

我需要用 11 个空格填充它,即我的输出应该是这样的:

'           01234567' 
'           09876544'
'           12345676'
'           34576980'
Run Code Online (Sandbox Code Playgroud)

我如何使用 UNIX shell 脚本来做到这一点?

Dan*_*son 11

我假设/猜测撇号不应该包含在输出中。

标准 shell 解决方案,infile包含输入的文件在哪里:

while read i; do printf "%19s\n" "$i"; done < infile
Run Code Online (Sandbox Code Playgroud)

其中19是每行的字符串长度(8)加上想要的填充(11)。我再次猜测这种填充是您想要的,而不仅仅是在所有行前添加 11 个空格。如果不是这种情况,您需要给出一个具体示例,说明应如何处理不同长度的输入行。

如果要包含撇号:

while read i; do printf "'%19s'\n" "$i"; done < infile
Run Code Online (Sandbox Code Playgroud)


小智 6

来自 GNU coreutils 的一个较短的选项是pr命令:

pr -T -o 11 foo.txt
Run Code Online (Sandbox Code Playgroud)

摘自手册页:

DESCRIPTION
       Paginate or columnate FILE(s) for printing.

       -o, --indent=MARGIN
              offset each line with MARGIN (zero) spaces

       -T, --omit-pagination
              omit page headers and trailers, eliminate any pagination by form feeds set in input files
Run Code Online (Sandbox Code Playgroud)