bash & Printf : How can I both right pad and truncate?

标签 bash printf padding truncate

在 Bash 中...

我知道如何用 printf 右填充

printf "%-10s" "potato"

我知道如何用 printf 截断

printf "%.10s" "potatos are my best friends"

我怎样才能同时做这两件事?

LIST="aaa bbbbb ccc ddddd"
for ITEM in $LIST; do
  printf "%-.4s blah" $ITEM
done

这打印

aaa blah
bbbbb blah
ccc blah
ddddd blah

我要打印

aaa  blah
bbbb blah
ccc  blah
dddd blah

我宁愿不做这样的事情(除非没有其他选择):

LIST="aaa bbbbb ccc ddddd"
for ITEM in $LIST; do
  printf "%-4s blah" $(printf "%.4s" "$ITEM")
done

不过,很明显,这行得通(感觉很丑陋而且很老套)。

最佳答案

您可以使用 printf "%-4.4s 在输出中获取两种格式:

for ITEM in $LIST; do printf "%-4.4s blah\n" "$ITEM"; done
aaa  blah
bbbb blah
ccc  blah
dddd blah

关于 bash & Printf : How can I both right pad and truncate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350992/

相关文章:

latex 填充物/边缘 hell

bash - 如何在AWK中整理多个文件?

linux - 在 linux 中通过 bash shell 脚本更新 phpMyAdmin blowfish_secret

bash - 使用最大进程数并行化 Bash 脚本

bash - 每次音量为零时,如何使用 ffmpeg 分割 mp4 视频?

perl - 如何执行 64 位十六进制/十进制算术并将十六进制中的完整数字作为字符串在 Perl 中输出?

linux - 在汇编中使用 printf 会导致管道传输时输出为空,但可以在终端上使用

c - 检测 Visual C++ 中存在哪个版本的 vswprintf()

jQuery 将 padding-top 计算为 px 中的整数

css - 当 float 对象元素在内部时填充