如果line比x chars cut更长并添加字符串

时间:2017-03-25 08:52:18

标签: linux bash shell

我是bash的新手,我试图解决一个问题。 我知道已经回答了类似的问题,但答案太复杂了。

我有一个包含多行的变量,我需要剪切超过40个字符的每一行并添加" ...:"在它之后。

但如果该行短于40个字符,我需要将其设为长40个字符并仅添加" :"

所以它看起来像这样:

var=this line is longer than 40 characters so it needs to be cut
but this line is shorter

我需要它看起来像这样:

echo "$var"
this line is longer than 40 characters s...: 
but this line is shorter                   :

在我的实际变量中总共有10行

3 个答案:

答案 0 :(得分:1)

您可以在printf中使用awk

awk 'length > 40{$0 = substr($0, 1, 40) "..."} {printf "%-43s:\n", $0}' <<< "$var"

this line is longer than 40 characters s...:
but this line is shorter                   :

或者让它从命令行接受参数:

awk -v n=40 -v r='...' 'length > n{$0 = substr($0, 1, n) r}
{printf "%-" n + length(r) "s:\n", $0}' <<< "$var"

this line is longer than 40 characters s...:
but this line is shorter                   :

答案 1 :(得分:0)

AWK 方法:

echo $var | awk '{printf("%-40s"((length($0)>40)?"...":"   ")":\n", substr($0,1,40))}'

输出:

this line is longer than 40 characters s...:
but this line is shorter                   :

答案 2 :(得分:0)

或者我们可以留在bash:

var='this line is longer than 40 characters so it needs to be cut
but this line is shorter'

while IFS=$'\n' read -r line
do
    if (( ${#line} > 36 ))
    then
        line="${line:0:36}...:"
    else
        (( diff = 40 - ${#line} ))
        printf -v line "%s%${diff}s\n" "$line" "...:"
    fi

    echo "$line"
done<<<"$var"

显然其他命令如awk可以做得更短:)

还不清楚整行是40个字符还是40行加上额外的'...:'。很容易改变:)