I'm having a bit of trouble with grep and hope someone can help. I need to match strings that include a hyphen, but there are similar strings without it. For example, I want to run a command like `echo "test-case another-value foo" | grep -Eom 1 "test-case"` to get `test-case`, but when I try to search for just `test` using `echo "test-case another-value foo" | grep -Eom 1 "test"`, it returns `test` instead. I want to avoid getting `test` in my results. Additionally, I sometimes need to search for `foo` as well. Any ideas on how I can achieve this?
5 Answers
I noticed you're asking `grep` to return `test` in your second example, which is why it gives you that output. Just remember, if you want to exclude it, make sure you don’t include `test` in your queries at all!
It’s amusing that there's no way to modify the word character set for `grep -w`. I think it's strange that it only considers underscores as word characters by default.
I found that to be strange as well. It should support more characters!
You can try running `grep -Eom 1 -- "test-case"` directly. Make sure your syntax is correct, as sometimes small errors can lead to unexpected results.
I tried this command, but I was getting inconsistent results.
When you use `grep` with the `-o` option, it only outputs exact matches based on your search pattern. Your examples don't really utilize regex, so using `-E` might not be necessary. It seems like you're looking for full words, likely whitespace-delimited, but want to search for incomplete patterns at times.
If your version of grep supports it, try using `--perl-regexp` instead of `-E`. This way, you can apply some lookahead and lookbehind assertions. For instance:
```
echo 'test-case another-value foo' | grep --perl-regexp --only-matching --max-count=1 '(?<!S)test-case(?!S)'
echo 'test-case another-value foo' | grep --perl-regexp --only-matching --max-count=1 '(?<!S)test(?!S)'
```
This should help you strictly match the whole `test-case` string without accidentally catching `test`.
Worked beautifully! Thank you internet stranger.
Because `test` and `test-case` are placeholders for actual deployment names. Sometimes we have deployments with similar names, and I've used the `-w` switch in the past but it doesn't work well with hyphens.