我试图将某些命令的输出限制到终端宽度的末尾。如果超过终端尺寸,则将超出的字符加上几个以上的点。
我无法固定解决方案,只是长时间待在身边。这是一个例子:
echo $x
this is a sample string and this does not mean anything this is to feed length
echo $x |awk '{print length($0)}' #Here terminal size is greater then line's length.
78
终端尺寸:
tput cols
168
但是,如果我有一个较小的窗口:
tput cols
74
然后$x
的内容将分为两行,我希望多余的字符被清除掉。
因此,如果终端大小为74,则$x
应打印为:
echo $x
this is a sample string and this does not mean anything this is to feed ..
我正在考虑实施,但我现在迷失了。
echo $x |awk --posix -v c=$(tput cols) '{l=length($0);if(l>c) {difference=l-c ;gsub(/.\{difference\}$/,"",$0);print $0}else print $0}'
this is a sample string and this does not mean anything this is to feed length
答案 0 :(得分:3)
这样的事情?
... | awk -v t=$(tput cols) '{if(length($0)>t) print substr($0,1,t-4) "...";
else print}'
答案 1 :(得分:1)
代码中的错误解释
echo $x \
| awk --posix -v c=$(tput cols) '
{
l = length($0)
if( l > c ) {
# difference = l - c
# variable difference is not interpretated in regex format
# $0 is the default variable of (g)sub
# gsub(/.\{difference\}$/,"",$0)
# gsub( ".{" difference "}$","", $0)
sub( ".{" ( l - c + 3 ) "}$","...")
# print $0
}
# else print $0
}
#print
7
'
答案 2 :(得分:0)
您也可以在简单的作业中使用karakfa的想法:
... | awk -v c=$(tput cols) '$0 = length > c ? substr($0,1,c-4) : $0'