【问题标题】:How do I justify text in bash?如何在 bash 中证明文本的合理性?
【发布时间】:2014-10-13 17:08:53
【问题描述】:

什么命令可以根据终端宽度证明文本的合理性?例如:

text is here text is here text is here text is here text is 
here text is here text is here text is here text is here text
is here text is here text is here text is here

我想打印:

   text is here text is here text is here text is here text is
 here text is here text is here text is here text is here text
                is here text is here text is here text is here

【问题讨论】:

  • 您希望它右对齐到最长行的长度还是屏幕的宽度? (这两个答案在这一点上有所不同,我不清楚哪个是正确的)。
  • @CharlesDuffy:从预期输出的外观来看::从第一列开始的第二行告诉我,最长的行被用作对齐边距。
  • @CharlesDuffy 到屏幕的宽度
  • 嗯,你编辑了你的问题。无论如何,在这种情况下,您应该接受@thatotherguy 的回答
  • @anubhava 是的,很抱歉。我没有注意到我写了错误的输出。

标签: linux bash shell unix terminal


【解决方案1】:

使用printf对齐,tput cols获取终端宽度:

width=$(tput cols)
while IFS= read -r line
do 
  printf "%${width}s\n" "$line"
done << EOF
text is here text is here text is here text is here text is
here text is here text is here text is here text is here text
is here text is here text is here text is here
EOF

改为从文件居中对齐:

width=$(tput cols)
while IFS= read -r line
do 
  printf "%$((width/2 - ${#line}/2))s%s\n" "" "$line"
done < file

【讨论】:

  • @CharlesDuffy 可能是因为默认情况下不会导出 COLUMNS。我将其编辑为使用tput cols
  • 确认您在这一点上是正确的。不得不说我有点糊涂了,但是……耸耸肩
  • @thatotherguy 如果我希望文本以终端宽度为中心,如何更改此代码?另外,如果我需要从文件中读取它,如何更改它?谢谢。
  • @Godfryd 这确实是一个不同的问题,但我更新了答案。
【解决方案2】:
  • 使用gnu wc 获取文件中的最大行长度
  • 使用printf 右对齐输出

脚本:

max=$(wc -L < file) && while read -r p; do printf "%${max}s\n" "$p"; done < file
  text is here text is here text is here text is here text is
here text is here text is here text is here text is here text
               is here text is here text is here text is here

【讨论】:

  • 如果我希望文本居中,如何更改?谢谢。
  • 这可以用更多的代码来完成,see this answer
【解决方案3】:

这是我的解决方案:

width=$(tput cols)
fmt -w $width | xargs -i printf "%${width}\n" {}

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多