複数行文字列の長さ

複数行文字列の長さ

以下のように複数行の文字列があります。

"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

おすすめ記事