Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of shortest line?

Tags:

linux

shell

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?

like image 509
sam Avatar asked Sep 26 '12 10:09

sam


4 Answers

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.

like image 73
Sergey Avatar answered Nov 15 '22 16:11

Sergey


Pure awk solution:

awk '(NR==1||length<shortest){shortest=length} END {print shortest}' file
like image 12
dogbane Avatar answered Nov 15 '22 15:11

dogbane


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 "

like image 1
Bob23 Avatar answered Nov 15 '22 16:11

Bob23


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
$ 
like image 1
HermannSW Avatar answered Nov 15 '22 15:11

HermannSW