2012-09-26 24 views
6

En el comando Linux usando wc -L es posible obtener la longitud de la línea más larga de un archivo de texto.¿Longitud de la línea más corta?

¿Cómo puedo encontrar la longitud de la línea más corta de un archivo de texto?

+0

http://superuser.com/q/135753/109661 – hovanessyan

Respuesta

11

Prueba esto:

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

Este comando obtiene longitudes de todos los archivos, los ordena (correctamente, como números) y, fianlly, imprime el número más pequeño a la consola.

10

solución pura awk:

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

Esto parece un poco más rápido. – ADTC

0

Me di el comando awk en una función (por bash):

function shortest() { awk '(NR==1||length<shortest){shortest=length} END {print shortest}' $1 ;} ## report the length of the shortest line in a file

añadido esto a mi .bashrc (y luego "fuente Bashrc ")

y luego lo ejecutó: el más corto" yourFileNameHere "

[~]$ shortest .history 
2

se puede asignar a una variable (Observe que hacen falta backtics):

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

Para CSH:

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

0

Ambos awk soluciones de arriba no manejan '\ r' el camino wc -L hace. Para un archivo de entrada de una sola línea, no deben producir valores superiores a la longitud de línea máxima informada por wc -L.

Esta es una solución nueva sed base (I no fue capaz de acortar mientras se mantiene correcta):

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

He aquí algunos ejemplos, mostrando '\ r' reclamación y demostrando sed solución:

$ 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 
$ 
Cuestiones relacionadas