Compare the two files line by line and find the largest and smallest number using shell scripts

I have two files, both of which have one number per line and must compare both files to find the largest and smallest numbers.

eg: -

file1

2
34
5

file2

44
5
66
4

you need to get 66 as the largest number, and 2 as the smallest number.

If someone tells me about the commands that I need to focus on, this will be the help of the lattice, as I just started to learn shell scripts.

+3
source share
4 answers

You can use:

sort -n file1 file2 > _sorted.tmp
min=$(head -1 _sorted.tmp)
max=$(tail -1 _sorted.tmp)

Without a temporary file:

arr=( $(sort -n file1 file2) )
min=${arr[1]}
max=${arr[@]:(-1)}
+5
source

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

sed '/^$/d' , 100% , . , unique sort.

, :

sort --numeric nu1 nu2 | sed -n '1p;$p'

:

sort -n nu1 nu2 | sed -n '1p;$p'
+2

There may be one liner if you do not want to keep the value

sort -n file1 file2 | head -1 sort -n file1 file2 | tail -1

+1
source

Usage awk:

$ head f1 f2
==> f1 <==
10
32
14

==> f2 <==
9
42
4

$ awk 'NR==1{min=$1;max=$1}
{max=(max>$1)?max:$1;min=(min<$1)?min:$1}
END{print "max is: "max; print "min is: "min}' f1 f2
max is: 42
min is: 4
0
source

All Articles