Muhammad Mustafa
Muhammad Mustafa

Reputation: 35

reading and analyzing a text file with bash script

I want to read a log file and want to extract 5-6 number digit that is written right next after the keyword "salary". And then want to analyze if the salary is above 2000. If there is even one above 2000, it is a MNC otherwise unknown. After writing the salary, the line ends mostly but sometimes there is an email option.

My script currently looks like this.

salary=$(grep -o 'salary [1-9][0-9]\+$' tso.txt | grep -o '[0-9]\+')

echo $salary

if [ $salary >  2000 ]; then echo "it is mnc....."; else ":it is unknown....."; fi


Upvotes: 1

Views: 452

Answers (2)

anubhava
anubhava

Reputation: 785196

This can be done in a simple awk like this:

awk '
{
   for (i=2; i<=NF; ++i)
      if ($(i-1) == "salary" && $i+0 > 2000) {
         mnc = 1
         exit
      }
}
END {
   print (mnc ? "it is mnc....." : "it is unknown.....")
}' file

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626896

As you seem to be using a GNU grep, you can get the salary value directly with grep -oP 'salary *0*\K[1-9][0-9]*' and then you can check the salary with if [ $salary -gt 0 ].

See the online demo:

#!/bin/bash
tso='salary 23000'
salary=$(grep -oP 'salary *0*\K[1-9][0-9]*' <<< "$tso")
echo $salary # => 23000

if [ $salary -gt  0 ]; then
  echo "it is mnc.....";
else
  echo "it is unknown....."; 
fi
# => it is mnc.....

Upvotes: 0

Related Questions