I\'m looking for a simple way to find the length of the longest line in a file. Ideally, it would be a simple bash shell command instead of a script.
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"
If you are using MacOS and are getting this error:
wc: illegal option -- L
you dont need to install GNU sipmly do this.
If all you want to do is just get the count of the characters in the longest line of the file and you are using OS X run:
awk '{print length}' "$file_name" | sort -rn | head -1
Something like this;
echo "The longest line in the file $file_name has $(awk '{print length}' "$file_name" | sort -rn | head -1) characters"
Outputs:
The longest line in the file my_file has 117 characters
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
Variation on the theme.
This one will show all lines having the length of the longest line found in the file, retaining the order they appear in the source.
FILE=myfile grep `tr -c "\n" "." < $FILE | sort | tail -1` $FILE
So myfile
x
mn
xyz
123
abc
will give
xyz
123
abc