I have two files which both have one number per line and need to compare both files to find the largest and smallest numbers.
eg:-
file1
2
34
5
file2
44
5
66
4
need to get 66 as largest number and 2 as smallest number.
If anyone guides me about the commands i need to focus on, that will be a grate help as I just started to learn shell scripting.
You can use:
sort -n file1 file2 > _sorted.tmp
min=$(head -1 _sorted.tmp)
max=$(tail -1 _sorted.tmp)
Without temporary file:
arr=( $(sort -n file1 file2) )
min=${arr[1]}
max=${arr[@]:(-1)}
Chain reaction:
sort --numeric --unique nu1 nu2 | sed '/^$/d' | sed -n '1p;$p'
| | | | | | | | |
| | | | | | | | +---- print last
| | | | | | | +------- print first
| | | | | | +----------- no print
| | | | | +----------------------- remove empty
| | | | +------------------------------------ file2
| | | +--------------------------------------- file1
| | +---------------------------------------------- unique
| +-------------------------------------------------------- numeric
+--------------------------------------------------------------- sort
The sed '/^$/d' part can be removed if you are 100% sure there are no empty lines in any of the files. If so, then unique can also be removed from sort.
In other words, meeting those two criterias this also works:
sort --numeric nu1 nu2 | sed -n '1p;$p'
As in short version:
sort -n nu1 nu2 | sed -n '1p;$p'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With