2

I have a multiline string as follows

"this is a sample
this is a second sample
same length the 1 above
this is a third sample"

Is there any way to find which line(s) have the maximum length (in terms of number of characters) and what is the length. In the sample above, that would be the second and third line.

  • Length in number of bytes or number of characters or in display width (or your sample, all 3 are the same but in the general case, they're not)? May the lines contain control characters like TAB or BS? – Stéphane Chazelas Sep 6 '17 at 14:17
  • @Stéphane Chazelas no of characters – wazza Sep 6 '17 at 14:20
  • What should happen if there are several lines with the max number of characters? – Stéphane Chazelas Sep 6 '17 at 14:20
  • just need to echo that line – wazza Sep 6 '17 at 14:20
  • You mean output all the lines that have the maximum number of characters? – Stéphane Chazelas Sep 6 '17 at 14:22
3
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}'

Outputs:

Max length: 23
2: this is a second sample
3: same length the 1 above
| improve this answer | |
0
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

gives you the list of lines with length, sorted by length

| improve this answer | |
0

Total statistics with top longest lines using GNU awk solution:

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

The output:

Length: 23, row number(s): 2, 3
Length: 22, row number(s): 4
Length: 16, row number(s): 1
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.