Sriharsha Kalluru
Sriharsha Kalluru

Reputation: 1823

Match exact word using grep

I have a requirement to search for an exact word and print a line. It is working if I don't have any . (dots) in the line.

$cat file
test1 ALL=ALL
w.test1 ALL=ALL

$grep -w test1 file
test1 ALL=ALL
w.test1 ALL=ALL

It is giving the second line also and I want only the lines with the exact word test1.

Upvotes: 1

Views: 35036

Answers (5)

Master
Master

Reputation: 59

grep -wi 'test1' file

This will work

Upvotes: 2

Naga Sai
Naga Sai

Reputation: 1

You can take below as sample test file.

$cat /tmp/file
test1 ALL=ALL    
abc test1 ALL=ALL    
  test1 ALL=ALL    
w.test1 ALL=ALL    
testing w.test1 ALL=ALL

Run below regular expression to search a word starting with test1 and a line that has a word test1 in between of line also.

$ grep -E '(^|\s+)test1\b' /tmp/file   
test1 ALL=ALL    
abc test1 ALL=ALL   
  test1 ALL=ALL

Upvotes: 0

salim khatib
salim khatib

Reputation: 26

I know I'm a bit late but I found this question and thought of answering. A word is defined as a sequence of characters and separated by whitespaces. so I think this will work grep -E ' +test1|^test1' file


this searches for lines which begin with test1 or lines which have test preceded by at least one whitespace. sorry I could find a better way if someone can please correct me :)

Upvotes: 0

Matt
Matt

Reputation: 74889

For your sample you can specify the beginning of the line with a ^ and the space with \s in the regular expression

grep "^test1\s" file

It depends on what other delimiters you might need to match as well.

Upvotes: 4

stevo81989
stevo81989

Reputation: 170

Try this:

grep -E "^test1" file

This states that anything that starts with the word test1 as the first line. Now this does not work if you need to fin this in the middle of line but you werent very specific on this. At least in the example given the ^ will work.

Upvotes: 6

Related Questions