How Can I Use Grep to Match Specific Strings with Hyphens?

April 23, 2025 5 answers
Asked by JAZZ HANDS
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?

Answers

12 bead necklace
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`.

mango peel method: Worked beautifully! Thank you internet stranger.

Reply to this answer
rather peculiar
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.
Reply to this answer
!check the collar~
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.

JAZZ HANDS: I tried this command, but I was getting inconsistent results.

Reply to this answer
sketchbook 82
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.

!check the collar~: I found that to be strange as well. It should support more characters!

Reply to this answer
district.boundaries
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!

JAZZ HANDS: 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.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions