sam
sam

Reputation: 405

Length of shortest line?

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?

Upvotes: 11

Views: 9599

Answers (4)

HermannSW
HermannSW

Reputation: 301

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
$ 

Upvotes: 1

Bob23
Bob23

Reputation: 11

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 "

Upvotes: 1

dogbane
dogbane

Reputation: 274758

Pure awk solution:

awk '(NR==1||length<shortest){shortest=length} END {print shortest}' file

Upvotes: 15

Sergey
Sergey

Reputation: 8248

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.

Upvotes: 15

Related Questions