
ローカル変数$ INPUTに長い複数行の入力文字列があります。たとえば、次のようになります。
a
b
c
d
e
f
最大n行に切り捨てる方法(n = 3と仮定して最後にメッセージを追加)
a
b
c
... message too long
これは私が持っているものですが、複数行では機能しません。
$OUTPUT=$('$INPUT' | awk '{print substr($0, 1, 15) "...")
答え1
どうですか?
output=$(echo "$input" | awk -v n=3 'NR>n {print "... message too long"; exit} 1')
または
output=$(echo "$input" | sed -e '3{a\... message too long' -e 'q}')
output=$(echo "$input" | sed -e '3{$!N;s/\n.*/\n... message too long/' -e 'q}')
POSIXとして
output=$(echo "$input" | sed -e '3{
$!N
s/\n.*/\n... message too long/
q
}')
またはGNU sedを使用してください。
output=$(echo "$input" | sed -e '4{i\... message too long' -e 'Q}')
答え2
OUTPUT=$(echo "$INPUT" | perl -pe '1..3 or exit')
答え3
私はこれを提供する:
# convert the variable into an array
$ mapfile -t arr < <(echo "$INPUT")
# use printf and slice the array into the fisrt three elements
$ printf "%s\n" "${arr[@]:0:3}" "... message too long"
a
b
c
... message too long