如何在bash中证明文本的合理性?

时间:2014-10-13 17:08:54

标签: linux bash shell unix terminal

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

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

3 个答案:

答案 0 :(得分:3)

使用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

答案 1 :(得分:3)

  • 使用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

答案 2 :(得分:0)

这是我的解决方案:

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