Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Longest line in a file

People also ask

What is the maximum length of a line in a text file?

Nonetheless, lines are simply delimited and may be any length. mode): 32767, otherwise 2147483647 characters. Longer lines are split. Maximum number of lines 2147483647 lines.

Which command will return the length of longest line in a file?

Display Length of Longest LineThe 'wc' command allow an argument '-L', it can be used to print out the length of longest (number of characters) line in a file.

How do you display length of the longest line from a given file?

We know that the grep command can match a pattern using the regex in a text file. If we know the longest line length as MAX_LEN, all longest lines should match the ERE pattern “^. {MAX_LEN}$“. Finding the maximum line length would then be the task of the wc command.

How do you find the longest line in Notepad ++?

You can look for lines longer than a given threshold as follows: Edit -> Find -> Select "Regular expression" in "Search Mode", look for . {x,} where x is your desired threshold (e.g. . {15,} to look for lines that are 15 characters or longer).


Using wc (GNU coreutils) 7.4:

wc -L filename

gives:

101 filename

awk '{print length, $0}' Input_file |sort -nr|head -1

For reference : Finding the longest line in a file


awk '{ if (length($0) > max) {max = length($0); maxline = $0} } END { print maxline }'  YOURFILE 

Just for fun and educational purpose, the pure POSIX shell solution, without useless use of cat and no forking to external commands. Takes filename as first argument:

#!/bin/sh

MAX=0 IFS=
while read -r line; do
  if [ ${#line} -gt $MAX ]; then MAX=${#line}; fi
done < "$1"
printf "$MAX\n"

wc -L < filename

gives

101

perl -ne 'print length()."  line $.  $_"' myfile | sort -nr | head -n 1

Prints the length, line number, and contents of the longest line

perl -ne 'print length()."  line $.  $_"' myfile | sort -n

Prints a sorted list of all lines, with line numbers and lengths

. is the concatenation operator - it is used here after length()
$. is the current line number
$_ is the current line


Looks all the answer do not give the line number of the longest line. Following command can give the line number and roughly length:

$ cat -n test.txt | awk '{print "longest_line_number: " $1 " length_with_line_number: " length}' | sort -k4 -nr | head -3
longest_line_number: 3 length_with_line_number: 13
longest_line_number: 4 length_with_line_number: 12
longest_line_number: 2 length_with_line_number: 11