简体   繁体   中英

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 .

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM