Mohammedz.com

For Linux and Shell scripting.

Find the largest number from a given file

Leave a comment


Here is a shell script to find the highest/largest number from a given input file.

Notes: The input file name numbers.txt contains only numbers in each line. It can be positive or negative numbers.

awk '$0>x{x=$0}; END {print "largest number="x}' numbers.txt

Here is a different version using explicit if statement..

awk '{if($0>x)x=$0; y=NR}; END {print "largest number="x}' numbers.txt

The following awk one-liner would give you position (line number) of the largest number as well. This might be useful at times.

awk '$0>x{x=$0; y=NR}; END {print "largest number="x"\nPosition(line number)="y}' numbers.txt

Yet another version using explicit loops (using while loop and if statements)

#!/bin/bash

largest=0

while read number; do

if [ $largest -lt $number ]; then

largest=$number

fi

done < numbers.txt

echo largest number = $largest

This version gives you largest number along with its position (using while loop and if statements)

#!/bin/bash

largest=0

count=1

while read number; do

if [ $largest -lt $number ]; then

largest=$number

position=$count

fi

count=$((count+1))

done < numbers.txt

echo largest number = $largest

echo position \(line number\) = $position

Here is another scenario where the input file has multiple fields with different data and you want to find the largest value of a specific field. Here is a sample file which has 4 fields and you want to find the largest value in 3rd field. Then print the matched line.

Notes: The input file doesn’t contain headings. I just included it below for your understand. And if it’s given in your input file, you have to remove them before you start the actual processing (using sed, head, tail etc). Also, the input file is a regular text file and so the fields are separated by space or tabs.

Name Matches Runs Wickets
Sachin 450 18000 150
Ganguly 300 11000 100
Azharuddin 334 9300 12
Dravid 344 10880 4

awk '$3>x{x=$3; line=$0}; END {print line}' input.txt

If you want to print only the player name and runs (matched field), here it is.

awk '$3>x{x=$3; y=$1}; END {print y " " x}' input.txt

Here is a script for same purpose using while loop and if statements.

#!/bin/bash

largest=0

while read name matches runs wickets; do

if [ $largest -lt $runs ]; then

largest=$runs

player=$name

fi

done < file.txt

echo highest runs = $largest

echo player name = $player

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s