gpt4 book ai didi

bash printf : how to understand zero dot s ("%0.s") syntax

转载 作者:行者123 更新时间:2023-12-04 02:52:34 24 4
gpt4 key购买 nike

使用 Bash printf,我不知道如何理解以下代码的语法。

echo $(printf "%0.s../"  2  ); 
# ../
echo $(printf "%0.s../" );
# ../
echo $(printf "%0.s../" 1 );
# ../

man printf 读取,

...

s
Bytes from the string argument are printed until the end is reached or until the number of bytes indicated by the precision specification is reached; however if the precision is 0 or missing, the string is printed entirely.

...

我还是不知道上面的代码。

为什么会重复打印以下代码?

# repeating character 
echo $(printf "%0.s../" 1 2 );
# ../../

https://wiki.bash-hackers.org/commands/builtin/printf

...

. The dot: Together with a field width, the field is not expanded when the text is longer, the text is truncated instead. "%.s" is an undocumented equivalent for "%.0s", which will force a field width of zero, effectively hiding the field from output

...

还没看懂。我需要一些解释。

最佳答案

这个例子可以阐明宽度字段的工作原理

printf '%.0s../\n' ABCDEFG
../
printf '%.1s../\n' ABCDEFG
A../
printf '%.2s../\n' ABCDEFG
AB../
printf '%.7s../\n' ABCDEFG
ABCDEFG../

当宽度为0时,则根本不打印该字段。

然后,如果参数多于字段,printf 重复格式

printf '%.7s../\n' ABCDEFG abcdefg
ABCDEFG../
abcdefg../

关于 bash printf : how to understand zero dot s ("%0.s") syntax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54396599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com