zeewagon
zeewagon

Reputation: 2033

How to read a file in shell script

I am new to shell scripting. I am trying to a script.

I have a log file, which saves the data every minute. The script needs to detect a keyword in that log file, if the keyword is present on it.

I was trying as below:

read jeeva/sample/logs.txt
grep keyword

I know my script is idiotic. Please help me with this.

Upvotes: 0

Views: 1720

Answers (3)

karakfa
karakfa

Reputation: 67467

perhaps you want to write it this way

$ if grep -q keyword jeeva/sample/logs.txt; 
  then echo "found"; 
  else echo "not found"; 
  fi

-q option is to suppress the output when the keyword is found.

Upvotes: 2

g-t
g-t

Reputation: 1533

I guess you just need to monitor some tagged log messages. How about:

tail -fn 1000 youFile.log | grep yourTag

Tail seems to be better in this case because you don't need to rerun it.

If you need script try this one:

#!/bin/bash

while IFS='' read -r line || [[ -n "$line" ]]; do
    if [[ $line == *"$2"* ]]; then
        echo "Do sth here.";
        echo "Like - I've found: $line";
    fi
done < "$1"

$1 is a file $2 is your tag

➜  generated ./script.sh ~/apps/apache-tomcat-7.0.67/RUNNING.txt UNIX
Do sth here.
Like - I've found:     access to bind under UNIX.

Upvotes: 2

James
James

Reputation: 4052

This will read a file into a variable

some_var=$(cat jeeva/sample/logs.txt)

But you don't need to do that. You only want to check for the word "keyword", so you can just

grep keyword jeeva/sample/logs.txt

In a script if that is found then $? will equal 0, otherwise it will equal 1.

So you can do:

grep keyword jeeva/sample/logs.txt
if ! [[ $? ]] 
then 
    echo found 
else
    echo "not found"
fi

Upvotes: 3

Related Questions