以下のように複数行の文字列があります。
"this is a sample
this is a second sample
same length the 1 above
this is a third sample"
どの行の最大長(文字数)と長さがどのくらいであるかを判断する方法はありますか?上記の例では、2番目と3番目の行になります。
答え1
string="this is a sample
this is a second sample
same length the 1 above
this is a third sample"
printf '%s\n' "$string" | awk -v max=-1 '
{l = length}
l > max {max = l; output = "Max length: " max RS}
l == max {output = output NR ": " $0 RS}
END {if (max >= 0) printf "%s", output}'
出力:
Max length: 23
2: this is a second sample
3: same length the 1 above
答え2
echo "this is a sample
this is a second sample
this is a third sample" | \
while read line; do
echo ${#line} $line
done | sort -n
長さでソートされた長さの行のリストを提供します。
答え3
総統計トップGNUを使用する最も長い行アッ解決策:
awk 'BEGIN{ PROCINFO["sorted_in"]="@ind_num_desc" }
{ len=length; a[len]=(a[len])? a[len]", "NR:NR }
END{ for(i in a) printf "Length: %s, row number(s): %s\n",i,a[i] }' file
出力:
Length: 23, row number(s): 2, 3
Length: 22, row number(s): 4
Length: 16, row number(s): 1