使用 bash 创建缩进文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/461074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating indented text with bash
提问by Karl Yngve Lerv?g
I want to print a list to screen in a readable way. I use a loop to go through each element and make a new list which is formatted with commas and newlines. The problem is that in the first line of the output, I want a title. E.g., I want to print something like this:
我想以可读的方式打印列表以进行筛选。我使用循环遍历每个元素并创建一个新列表,该列表格式为逗号和换行符。问题是在输出的第一行,我想要一个标题。例如,我想打印这样的东西:
List: red, green, blue, black, cars,
busses, ...
The problem is to create the indentation in the second and following lines. I want the indentation to be of a given length. Therefore the problem is reduced to creating an empty line of a given length. That is, I want a function, create_empty_line_of_length, that outputs the given amount of spaces.
问题是在第二行和以下行中创建缩进。我希望缩进具有给定的长度。因此,问题简化为创建给定长度的空行。也就是说,我想要一个函数,create_empty_line_of_length,输出给定数量的空格。
length=5
echo "start:$(create_empty_line_of_length $length) hello"
The output should in this case be:
在这种情况下,输出应该是:
start: hello
Does anyone know how to do this?
有谁知道如何做到这一点?
采纳答案by squadette
It'll be
这将是
yes ' ' | head -7 | tr -d '\n'
Change '7' into your number.
将“7”更改为您的号码。
Maybe you should take a look at
也许你应该看看
man fmt
also.
还。
回答by Kent Fredric
printf '%7s'
Will probably the most efficient way to do it.
将可能是最有效的方法。
Its a shell builtin most of the time, and if not /usr/bin/printf exists as a fallback from coreutils.
大多数时候它是一个内置的 shell,如果不是,/usr/bin/printf 作为 coreutils 的后备存在。
so
所以
printf '%7s%s\n%7s%s\n' '_' 'hello' '_' 'world'
produces
产生
_hello
_world
( I used _ instead of space here, but space works too because bash understands ' ' )
(我在这里使用了 _ 而不是空格,但空格也有效,因为 bash 理解 ' ' )
回答by squadette
Not sure if this is going to help you http://unstableme.blogspot.com/2008/12/awk-formatting-fields-into-columns.html
不确定这是否会帮助你http://unstableme.blogspot.com/2008/12/awk-formatting-fields-into-columns.html

