Linux Shell - Sort a text file by the length of each line, then print the shortest line
Solution 1:
The commands
line_num=0
while IFS= read -r line
do
echo "${#line} $((++line_num)) $line"
done < file.txt > tmpfile.txt
will create a file called tmpfile.txt
, which looks like this:
20 1 This is many letters
11 2 This is few
2 3 Hi
29 4 This is a very long sentence.
where each line is preceded by its length and its line number.
Then sort -n tmpfile.txt
will yield:
2 3 Hi
11 2 This is few
20 1 This is many letters
29 4 This is a very long sentence.
which is sorted by line length.
You can then send that to head -n1
to get the first line
(i.e., the shortest line)
or tail -n1
to get the last line (i.e., the longest line).
Or use sort -nr
to reverse the order,
so you can use head -n1
to get the longest line.
(This might be infinitesimally more efficient than using tail
.)
If you want to see only the shortest line, you can use a pipe and avoid creating the temporary file:
line_num=0
while IFS= read -r line
do
echo "${#line} $((++line_num)) $line"
done < file.txt | sort -n | head -n1
This would probably be more efficient in awk
.