The length of the shortest line?

In a Linux command, using wc -L you can get the length of the longest line of a text file.

How to find the length of the shortest text file?

+6
source share
4 answers

Try the following:

 awk '{print length}' <your_file> | sort -n | head -n1 

This command gets the length of all files, sorts them (correctly, like numbers) and, fianlly, prints the smallest number for the console.

+11
source

Pure awk solution:

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

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: the shortest "yourFileNameHere"

  [~] $ shortest .history
 2 

It can be assigned to a variable (note that reverse processing is required):

  [~] $ var1 = `shortest .history`
 [~] $ echo $ var1
 2

For csh:

alias shortest "awk '(NR==1||length<shortest){shortest=length} END {print shortest}' \!:1 "

0
source

Both awk solutions above do not handle the '\ r' path of wc -L . For a single-line input file, they should not create values ​​that exceed the maximum line length reported by wc -L .

This is a new sed based solution (I could not shorten, while maintaining the correctness):

 echo $((`sed 'y/\r/\n/' file|sed 's/./#/g'|sort|head -1|wc --bytes`-1)) 

Here are a few examples showing the "\ r" claim and a demonstration of the 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 $ 
0
source

Source: https://habr.com/ru/post/926303/


All Articles