2017-03-25 29 views
-1

我都是新來的bash,我試圖解決一個問題。 我知道已經有類似問題的答案,但答案太複雜了。如果行比x字符長,並添加字符串

我有一個變量與多行,我需要削減每行超過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號線整體

+0

您的第二個預期的行有44個字符'但這一行更短:' – RomanPerekhrest

+1

它有40個字符,但三個空格,並且::在結尾添加而不是添加「...:」 – Buri

回答

1

可以在awk使用printf

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

這爲我工作!非常感謝! – Buri

+1

@anubhava,這是這個問題的一個很好的答案。你可以通過用變量替換43來使它更通用嗎?我的意思是允許可變的右填充。 – VM17

+1

好點@ VM17我在回答中添加了相同命令的通用版本。 – anubhava

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     : 
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該行加上額外的'...:'。容易改變:)