1

I want that line from the file which have highest length among all the lines using awk command.

Hauke Laging
  • 88,146
  • 18
  • 125
  • 174
Shah Honey
  • 74
  • 3
  • What is your definition of "highest length"? You say you want multiple lines, does that mean like "Top 5 highest length"? – jesse_b Apr 28 '18 at 14:33
  • I read it as “if there’s a tie, all the longest lines” – Jeff Schaller Apr 28 '18 at 14:34
  • No I only want that "line which has higher length among all the lines" and "if there is tie then all the longest line" – Shah Honey Apr 28 '18 at 15:24
  • "higher" is a comparative word, and as such needs qualification. Do you mean "highest", i.e. the "longest line or joint-longest lines"? – roaima Apr 28 '18 at 15:33
  • @Shah, if the lines in the file were "ab", "cd", and "e", what is your expected result? – Jeff Schaller Apr 28 '18 at 16:13
  • 1
    there are other solutions in that question that handle more than one line with max length... in gawk as well as other tools – Sundeep Apr 28 '18 at 16:20

2 Answers2

0
awk '{ if (length($0)>maxlength) { maxlength=length($0); longest_line=$0; } };
     END { print longest_line; }' inputfile
Hauke Laging
  • 88,146
  • 18
  • 125
  • 174
0

Check length of line (if no arguments passed to the length function it uses $0, the whole line).

Where length is greater than variable x, set x to the length. And set variable a to the contents of the line.

Finally, on reaching end of file, print the contents of variable a.

awk 'length>x{x=length;a=$0}END{print a}' inputfile

Try it online!

steve
  • 21,582
  • 5
  • 48
  • 75