简体   繁体   English

使用printf在bash中格式化多行命令输出

[英]Format multiline command output in bash using printf

My Bash script uses printf to print output of some other commands with formatting applied, in the following manner (note the two leading spaces): 我的Bash脚本使用printf以以下方式打印应用了格式设置的其他一些命令的输出(请注意两个前导空格):

printf "  %-16s %s\n" "foo:" "$(bar)"

The two leading spaces are there, because the first line in the file is a comment, and I like to keep things nicely aligned: 其中有两个前导空格,因为文件的第一行是注释,并且我希望保持对齐:

# foo
  foo:            bar
  foo:            bar
  ...

This works perfectly fine for commands with one-line output. 对于单行输出的命令,这非常好用。 However, when the output is multiline, the output looses the formatting of the subsequent lines. 但是,当输出为多行时,输出将松散后续行的格式。

For example: 例如:

printf "  %-16s %s\n" "Contents:" "$(ls -a)"

Results in something like this: 结果如下:

  Contents:       .
..
foo
bar

Instead, what I am trying to achieve is multiline output, with each line formatted (in columns, if you like), which would look like this (note the lack of "header" in the subsequent lines): 相反,我要实现的是多行输出,每行的格式设置为(如果需要,请设置为列),看起来像这样(请注意,后续各行中缺少“标题”):

  Contents:       .
                  ..
                  foo
                  bar

My understanding so far is that printf with two arguments (the first one being a string, and the other one the result of the given command) treats the second argument as a single string, which can include newline characters within. 到目前为止,我的理解是带有两个参数的printf (第一个参数是一个字符串,另一个参数是给定命令的结果)将第二个参数视为单个字符串,其中可以包含换行符。 Therefore, the output is actually correctly formatted, according to what I asked printf to do, but it is not what I am looking for. 因此,根据我要求printf执行的操作,输出实际上已正确格式化,但这不是我想要的。

I am aware about some of the pitfalls related to parsing the output of commands like ls , which exhausts my current possibilities of solving this problem. 我知道一些与解析ls之类的命令的输出有关的陷阱,这耗尽了我当前解决此问题的可能性。 Also, it is possible that printf is not the best facility to do this. 同样, printf可能不是执行此操作的最佳工具。

I am considering substituting multiline string into comma-separated list, if no solution to this problem is possible, but this would be a last resort. 如果无法解决此问题,我正在考虑将多行字符串替换为逗号分隔的列表,但这将是最后的选择。

What would be the best method to achieve the formatting I need? 什么是实现所需格式的最佳方法?

Thanks for your help. 谢谢你的帮助。

printf "  %-16s %s\n" "foo:" "$(bar | sed '2,$s/^/                   /g')"

You may find it difficult to apply the same print instructions to a range of commands. 您可能会发现很难将相同的打印指令应用于一系列命令。 Also output from ls can be tedious to examine because it selects an output format depending upon environment variables. ls的输出也可能很麻烦检查,因为它根据环境变量选择输出格式。

I found the following worked well for ls on my Mac: 我发现以下内容在Mac上适用于ls:

x=$(ls -a); 
x=${x//$'\n'/$'\n'                    }; 
printf "   %-16s %s" "Contents:" "$x" $'\n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM