grep for complete word doesn't work when the word contains a dash

时间:2017-04-25 09:49:50

标签: regex string grep

I am greping for a whole word using -w flag and it isn't working correctly. I am assuming it's because the source words contain a "dash" ("-") character:

echo "sdf-a" > /tmp/grep.txt
~/Developer : cat /tmp/grep.txt 
sdf-a

should not return anything:

cat /tmp/grep.txt | grep -w a
sdf-a <<<<<<<<<<<<<<< BAD

I've also tried with the "\" option:

cat /tmp/grep.txt | grep  "\<a\>"
sdf-a << Should not return it

When I remove the dash from the source word:

~/Developer/ : echo "sdfa" > /tmp/grep.txt
~/Developer/ : cat /tmp/grep.txt | grep  "\<a\>" // nothing returned as expected
~/Developer/ : cat /tmp/grep.txt | grep -w a // nothing returned as expected

1 个答案:

答案 0 :(得分:0)

使用一个小红宝石例程(为了我的目的),它将与多个破折号匹配:

def grep(file,val)
    res = []
    text = File.open(file).read
    text.each_line { |l|
      if l.include?(val)
        res.push(l)
      end
    }
    if res.count == 0
      return nil
    end
    return res
  end