How to find line with least characters
Here's a variant of an awk
solution for printing the first found minimum line:
awk '
NR==1 || length<len {len=length; line=$0}
END {print line}
'
which can simply be extended by one condition to print all minimum lines:
awk '
length==len {line=line ORS $0}
NR==1 || length<len {len=length; line=$0}
END {print line}'
'
With sqlite3
:
sqlite3 <<EOT
CREATE TABLE file(line);
.import "data.txt" file
SELECT line FROM file ORDER BY length(line) LIMIT 1;
EOT
A Perl way. Note that if there are many lines of the same, shortest length, this approach will only print one of them:
perl -lne '$m//=$_; $m=$_ if length()<length($m); END{print $m if $.}' file
Explanation
perl -lne
:-n
means "read the input file line by line",-l
causes trailing newlines to be removed from each input line and a newline to be added to eachprint
call; and-e
is the script that will be applied to each line.$m//=$_
: set$m
to the current line ($_
) unless$m
is defined. The//=
operator is available since Perl 5.10.0.$m=$_ if length()<length($m)
: if the length of the current value of$m
is greater than the length of the current line, save the current line ($_
) as$m
.END{print $m if $.}
: once all lines have been processed, print the current value of$m
, the shortest line. Theif $.
ensures that this only happens when the line number ($.
) is defined, avoiding printing an empty line for blank input.
Alternatively, since your file is small enough to fit in memory, you can do:
perl -e '@K=sort{length($a) <=> length($b)}<>; print "$K[0]"' file
Explanation
@K=sort{length($a) <=> length($b)}<>
:<>
here is an array whose elements are the lines of the file. Thesort
will sort them according to their length and the sorted lines are saved as array@K
.print "$K[0]"
: print the first element of array@K
: the shortest line.
If you want to print all shortest lines, you can use
perl -e '@K=sort{length($a) <=> length($b)}<>;
print grep {length($_)==length($K[0])}@K; ' file