bash 管道SEQ对printf为数字格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19148370/
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
piping seq to printf for number formatting
提问by Paolo
I'm trying to print the following pattern using printf and seq:
我正在尝试使用 printf 和 seq 打印以下模式:
0000
0001
0002
0003
My problem is once I use:
我的问题是一旦我使用:
seq 0 10 | xargs printf %04d
all my output is formatted into the same line likeso:
我所有的输出都被格式化为同一行,如下所示:
0000000100020003
I still can't get the hang of using xargs. How do I use it correctly in this case?
我仍然无法掌握使用 xargs 的窍门。如何在这种情况下,正确地使用它?
回答by Joni
The printf
command does not output a line break if you don't ask it to. Try:
printf
如果您不要求,该命令不会输出换行符。尝试:
seq 0 10 | xargs printf '%04d\n'
Note that you can achieve the same with just seq
, since it allows specifying a printf-style format:
请注意,您可以使用 just 实现相同的效果seq
,因为它允许指定 printf 样式的格式:
seq -f %04g 0 10
回答by Kent
you don't need printf
or xargs
. seq
has -f
option:
你不需要printf
或xargs
。seq
有-f
选项:
kent$ seq -f '%04G' 10
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
回答by unxnut
seq 0 10 | xargs printf "%04d\n"
The original question is missing the newline character at the end of the printf
. Simply adding a newline character fixes the issue.
原始问题缺少printf
.末尾的换行符。简单地增加一个换行符修复该问题。