@dos2unix - One minor adjustment -
@70 Tango Charlie wants the lowest 5 numbers.
The sort command posted will sort them from lowest to highest - so he will need to use
head -n 5
, NOT
tail -n 5
.
Tail would be appropriate if sort's -r option was used, which reverses the sort, sorting from highest to lowest. Then the last 5 numbers in the sequence would be appropriate.
So the options would be:
Bash:
sort -V numbers.txt | head -n 5 > lowestFive.txt
OR
Bash:
sort -Vr numbers.txt | tail -n 5 > lowestFive.txt
But the above would assume that each number is on a separate line in the file.
If Charlie exports the numbers to a comma separated file with the numbers in a single line like this:
numbers.txt
97, 84, 79, 88, 102, 89, 91, 78
OR:
97,84,79,88,102,89,91,78
Then it's a little more complicated. But not much.
What you'd need to do in that case is parse out the delimiters using something like sed or awk and then sort the numbers and isolate the lowest five..
e.g.
Using sed:
Bash:
sed 's/,/\n/g;s/ //g;' numbers.txt | sort -V | head -n 5
Above replaces commas with newlines and removes any spaces.
So effectively, each number is on its own line. Then we can run the
sort
command and use
head
to display the lowest 5.
NOTE: There are a number of other ways that this could be done. This is just one of them!
EDIT:
The only problem with the above solution is the numbers will all be on different lines.
In a script, you'd probably want something that reports the result in a single line.
So to put the above solution into a one-liner you could use in a script - you could do something like this:
Bash:
echo "The lowest five numbers in numbers.txt are: $(echo $(sed -e 's/,/\n/g;s/ //g;' numbers.txt | sort -V | head -n 5) | sed -e 's/\n/ /g')"
It's a little more complicated. We have some nested sub-shell's being invoked.
But it does it all in a single line.
The innermost sub-shell:
$(sed -e 's/,/\n/g;s/ //g;' numbers.txt | sort -V | head -n 5)
We've seen this already - this gets evaluated first - this yields our lowest 5 numbers.
But the numbers will be on separate lines.
Then the sub-shell surrounding it is evaluated:
$(echo $(lowest-5-result) | sed -e 's/\n/ /g')
NOTE:- Where
lowest-5-result
is actually the result of running the innermost sub-shell!
There is no variable called
lowest-5-result
, I've just substituted the entire expression in the innermost sub-shell with that, to represent its output when it is executed/evaluated!
That surrounding sub-shell strips out the newlines from our attempt to find the lowest 5 (innermost sub-shell), and replaces the newlines with spaces. So our lowest 5 numbers are now on the same line again.
Finally the echo command which encapsulates the two subshells are ran in the current shell. Displaying the message and the lowest 5 numbers:
e.g.
The lowest numbers in numbers.txt are: 78 79 84 88 89