How do I parse a line thorugh a file in bash
I am very new to shell scripting I had a small query regarding the file parsing.
So, here's what I am trying to do:
I run an svn merge command, and genaratea conflict file
my conflict file is stored as conflicts.txt
What I want to do is read this file line by line and parse one line to match against some keywords.
For example one of the line in files look like this:C Client/Game/src/test/test.php
Now I want to parse this line and search for the keyword test, in case I find it I want to do some action on it, for example aborting with exit status 2, 3, etc..
for example i want to iterate throught a text file called "FILENAME" which looks like this
30 '!' C Client/test.js
31 '!' C Client/test2.js
32 '!' C Client/test3.js`
what i am doing is catting the file using the while loop and cat commnad
cat $FILENAME | while read LINE
do
echo $LINE
done
here i am just printing the line , i want to know how can i search for a keyworkd in the line and if i find that keyword how can i do some action on it like exiting with status 1
Can you please suggest some way to do this..
33 Answers
There are many ways of doing this, depending on your needs.
Simply print all lines containing the keyword
test:grep test file.txtThe same but for many keywords. Create a file that has all the keywords, one per line and run
grep -f keywords.txt file.txtProcess a file line by line, exit if the line is found
while read line; do echo $line | grep test && break; done < file.txtExit with status 1 if the line matches. Unfortunately,if I remember correctly (not 100% sure), bash only allows you to set return values in functions. So, to get an exit status you need to use something else. Perl for example:
perl -ne '/test/ && exit(1)' file.txtThough you can't set an exit value, you can still do something similar with bash. The exit value of the last command run is always saved as
$?in bash, that means you can test the value of$?and act accordingly:while read line; do let c++; echo $line | grep test >/dev/null; if [[ $? == 0 ]] ; then echo Match for line $c : $line; else echo No match for line $c; fi done < file.txt
Simplest way is not to parse file line-by-line at all.
grep -q 'keyphrase' filename && exit <exitcode> 2 $ function some_action { echo found keyword
}
$ if grep -q -m1 -e 'test3' < input; then some_action fi
found keywordgrep options:
- -q: quiet; don't print matches
- -m1: exit after one match
- -e: expression (keyword)
e.g:
$ grep . input
30 '!' C Client/test.js
31 '!' C Client/test2.js
32 '!' C Client/test3.js
$ if grep -q -m1 -e 'test3' < input; then some_action ; fi
found keyword