Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

shell

unix

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.

like image 915
RoshanaSheri Avatar asked Dec 12 '25 03:12

RoshanaSheri


2 Answers

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)}
like image 72
anubhava Avatar answered Dec 14 '25 00:12

anubhava


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'
like image 35
user13500 Avatar answered Dec 14 '25 00:12

user13500



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!