Bash 如果终端长度小于使用awk的终端宽度,则将最后N个字符转换为点

Bash 如果终端长度小于使用awk的终端宽度,则将最后N个字符转换为点,bash,awk,Bash,Awk,我试图将某些命令的输出限制到终端宽度的末尾。如果超出端子尺寸,则将超出的字符加上几个字符替换为圆点 我不能把针放在解决方案上,只是从很久以前就开始了。以下是一个例子: 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 l

我试图将某些命令的输出限制到终端宽度的末尾。如果超出端子尺寸,则将超出的字符加上几个字符替换为圆点

我不能把针放在解决方案上,只是从很久以前就开始了。以下是一个例子:

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
像这样的

  ... | awk -v t=$(tput cols) '{if(length($0)>t) print substr($0,1,t-4) "...";
                                else print}' 

代码中的错误解释

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
    '

您也可以在简单的作业中使用karakfa的想法:

... | awk -v c=$(tput cols) '$0 = length > c ? substr($0,1,c-4) : $0'

就是这样。谢谢有一个问题…你能指出我的命令有什么错误吗?我觉得很好@PS wrt
/.\{difference\}$/
在您的代码中,您的两个真正的语义错误是:1)这是awk,而不是sed,因此ERE在默认情况下是启用的,因此您不会转义ERE元字符以启用它们,因为它们已经启用,转义将禁用它们-使用
{…}
,而不是
{…}
。2)
/…/
是一个regexp常量。在常量regexp中不能使用像
difference
这样的变量,您需要一个由字符串串联而成的动态regexp。请参阅。切勿将字母
l
用作变量名,因为它看起来太像数字
1
,因此会混淆代码。另外,当你有类似于
if(x){doy;doz}的代码时,如果你有其他的doz
,那么重构它到
if(x)doy;执行Z
,这样就不会复制公共代码。在您的代码中,这将是打印$0s。事实上,它导致赋值结果作为一个条件进行评估,然后用于确定是否应打印当前记录。如果输入行为空或为零或任何计算结果为零的内容,则不会打印出来,我怀疑这是不可取的。只有当您在评估条件的结果中有您想要的特定行为,并且完全了解副作用时,才将分配用作条件。哦,这可能会导致一些AWK上的语法错误,这是由于三元表达式的未细化。