LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   search for key word from a file (https://www.linuxquestions.org/questions/linux-newbie-8/search-for-key-word-from-a-file-4175426917/)

273 09-12-2012 03:21 PM

Quote:

Originally Posted by 2armz (Post 4778825)
hmm I might not be on the same page as you, i kinda understand what you are asking, but I'm new to this as well, so if i've thrown you off track sorry ;)

Hey, no problem.
I was really trying to ask brian00 how this was supposed to work so that I can understand it and he can double-check it is the right thing.
Personally I'd take away the '$' and replace 'ls' with 'cat' and try that.

273 09-12-2012 03:30 PM

OK, I just tried what I suggested and
Code:

#!/bin/bash
if [[ -n `cat log/output.tst | grep "MYDB"` ]] ; then
echo "found it!"
fi

results in
Code:

$ ./test.sh
found it!

If there is a match and nothing if there is not.
So to cheat you could echo whatever you wanted.
Of course there will be a way of using grep and regular expressions to do this properly.
The above is for illustrative purposes only to explain the logic I meant.

brian00 09-12-2012 04:13 PM

Thanks so much to everyone, specially 273 b/c it worked now.

one more question:

what if I want to add another string, basically, my condition is if both string exit then execute aything below it (both string has to exist)
Code:

#!/bin/bash
if [[ -n `cat log/output.tst | grep "MYDB" | grep "DUMMY"` ]] ; then
echo "found it!"
fi

test the above code and it doesnt' work.

273 09-12-2012 04:27 PM

This works but, again, it's not ideal and someone with a knowledge of scripting ought to be able to point out a correct solution:
Code:

#!/bin/bash
if [[ -n `cat log/output.tst | grep "MYDB"` ]] && [[ -n `cat log/output.tst | grep "DUMMY"` ]] ; then
echo "found it!"
fi

The logic of this is that you're using cat to pipe the file to grep, if you then just add another pipe to grep again as you did it will be working on the line returned by grep and not the whole file. I added a logical and so that both of the expressions need to be not null to enter the if statement.
Remember that the pipe | is just passing the result of the previous action not the whole file. This was my point about passing the result of ls to grep but I'm not familiar enough with the logic of bash to know whether there was an exception there somewhere.

chrism01 09-12-2012 08:43 PM

Code:

grep MYDB$ <filename here> |grep DUMMY
Matches MYDB at end of rec and 'DUMMY' must exist anywhere in same rec


All times are GMT -5. The time now is 03:21 AM.