In Linux command using wc -L
it's possible to get the length of longest line of a text file.
How do I find the length of the shortest line of a text file?
Try this:
awk '{print length}' <your_file> | sort -n | head -n1
This command gets lengths of all files, sorts them (correctly, as numbers) and, fianlly, prints the smallest number to console.
Pure awk solution:
awk '(NR==1||length<shortest){shortest=length} END {print shortest}' file
I turned the awk command into a function (for bash):
function shortest() { awk '(NR==1||length<shortest){shortest=length} END {print shortest}' $1 ;} ## report the length of the shortest line in a file
Added this to my .bashrc (and then "source .bashrc" )
and then ran it: shortest "yourFileNameHere"
[~]$ shortest .history 2
It can be assigned to a variable (Note the backtics are required):
[~]$ var1=`shortest .history` [~]$ echo $var1 2
For csh:
alias shortest "awk '(NR==1||length<shortest){shortest=length} END {print shortest}' \!:1 "
Both awk
solutions from above do not handle '\r' the way wc -L
does.
For a single line input file they should not produce values greater than maximal line length reported by wc -L
.
This is a new sed
based solution (I was not able to shorten while keeping correct):
echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1))
Here are some samples, showing '\r' claim and demonstrating sed
solution:
$ echo -ne "\rABC\r\n" > file
$ wc -L file
3 file
$ awk '{print length}' file|sort -n|head -n1
5
$ awk '(NR==1||length<shortest){shortest=length} END {print shortest}' file
5
$ echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1))
0
$
$ echo -ne "\r\r\n" > file
$ wc -L file
0 file
$ echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1))
0
$
$ echo -ne "ABC\nD\nEF\n" > file
$ echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1))
1
$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With