1836620 Members
1990 Online
110102 Solutions
New Discussion

Script to search a word

 
nash11
Frequent Advisor

Script to search a word

I am new to writing script , could give some advise how to write it?

I have a text file "printout.txt" , I want to check the content this file , if the word "failure" appear in this file for over two times , then do xxxxxxxx ,
what can I do ? thx
7 REPLIES 7
H.Merijn Brand (procura
Honored Contributor

Re: Script to search a word

That depends on how much you want to do with it.

0. Is the mere existance of the word enough to take action?
1. Is there more info on that line you need?
2. Is there more info in the surrounding lines you need?

In case 0, just use grep

if [ "`grep failure printout.txt`" == "" ]; then
echo no failure found
else
# Do some actions here
fi

If you want more security, use GNU grep and -w (grep whole word only)

If you need flexibility, use perl

#!/usr/bin/perl

use strict;
use warnings;

@ARGV = ("printout.txt");
while (<>) {
m/\b failure \b/x or next;
print STDERR "Found a failure on line $.\n";
system "echo Help | mailx -s failure you\@local.host";
}

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
nash11
Frequent Advisor

Re: Script to search a word

thx reply,

what I want is simple , if found the word "failure" appear OVER TWO TIMES in the file , then mail the message to me , what can I do ? thx.
Sergejs Svitnevs
Honored Contributor

Re: Script to search a word

awk -F"failure" 'BEGIN{cnt=0} {cnt+=(NF-1)} END{print cnt}' printout.txt

gives you the number of the word "failure" in the file.

Regards
H.Merijn Brand (procura
Honored Contributor

Re: Script to search a word

Several ways to count the number of lines with 'failures'

# perl -nle'/\bfailure\b/ and$n++}END{print$n' printout.txt

# grep -w failure printout.txt | wc -l

So, in a script, you could do

--8<---

n=`grep -w failure printout.txt | wc -l`
if [ $n -ge 3 ]; then
# actions here
fi
-->8---

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Hemmetter
Esteemed Contributor

Re: Script to search a word

Hi

Here another shell one-liner:

# [ $(grep -c failure printout.txt) -ge 2 ] && do_xxxxxxxx

rgds
HGH
H.Merijn Brand (procura
Honored Contributor

Re: Script to search a word

Did the answers help you? Did we interpret the question the way you meant it?

Enjoy, Have FUN! H.merijn
Enjoy, Have FUN! H.Merijn
Arturo Galbiati
Esteemed Contributor

Re: Script to search a word

Hi,
this runs on my hp-ux 11i:

cat printout.txt
failure hgjhjhk
failured
jkjk failure
klkl


if [[ $(grep -cw failure printout.txt) -ge 2 ]]; then
echo found more them 2 failure
fi

HTH,
Art