1

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sriharsha Kalluru
  • 1,743
  • 3
  • 21
  • 27
  • 1
    Should it be `grep -e '(^| )test1( |$)' file`, perhaps? I'm a bit confused by what you meant by 'exact word' here; because, yes, `w.test` is matched by `'[[:<:]]test1[[:>:]]'` pattern. – raina77ow Oct 03 '12 at 23:51

5 Answers5

6

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.

stevo81989
  • 170
  • 1
  • 9
  • Thanks that logic works and if the word is a starting word of the line. Is there any option if the words are in middle of the line which we are searching for. – Sriharsha Kalluru Oct 04 '12 at 10:27
  • This grep would also match words only starting with test1. e.g. test12. In any case, raina77ow's comment is the complete regex for matching a word at the beginning, middle or end of a file. `grep -e '(^| )test1( |$)' file` – Matt Oct 04 '12 at 16:50
4

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.

Matt
  • 68,711
  • 7
  • 155
  • 158
0

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 :)

  • 1
    It would match `test11` as well. I would recommend using -w (word grep option): grep -w test1 – grundic May 09 '17 at 18:28
0

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
shellter
  • 36,525
  • 7
  • 83
  • 90
Naga Sai
  • 1
  • 1
0
grep -wi 'test1' file

This will work

Master
  • 29
  • 1
  • 10