Mat
Mat

Reputation: 21

grep in ubuntu for text occurrence

I currently have a text file which contains the following lines of text in it. I need to use grep to display the number of lines the word test appears in the file for different scenario. Below are some things I have tried, but the output is wrong. I am pretty new to using grep, so hope someone could assist to advice where I have done wrong.

test.txt:

this is some testing for my own test purpose.

testing testing testing 1 2 3 test

test-case 1 is for delete purpose

tester’s is coming to test out the new devices

Tester test 3 test case

Scenario 1:

Report on how many lines in the text file test contain the case-sensitive word “test”. It should not include count of word that is a substring of another word. E.g testing, tester’s, test-case

Ans: grep “\btest\b” test | wc -l

Scenario 2:

Report on how many times the case-sensitive word “test” appears in the text file test (within other words is ok)

Ans: grep –o “test” test | wc -w

Scenario 3:

Report on how many times the word “test” appears in the last 2 lines of the text file test

Ans: tail –n 2 test | grep –o “\btest\b” | wc -w

Upvotes: 0

Views: 142

Answers (1)

Gautam
Gautam

Reputation: 1932

You can try the following :

Scenario 1:

$ grep -i -c "[^a-z]test[^a-z]" test.txt

Scenario 2:

$ grep –o “test” test.txt | wc -l

Scenario 3:

$ tail -2 test.txt | grep -o "[^a-z]test[^a-z]" | wc -l

Upvotes: 1

Related Questions