user2824889
user2824889

Reputation: 1185

Using grep to find matches of a string without a specific character at the end

I'm trying to use grep to find non-plural instances of a particular string.

For example, I want to find all instances of "string", but leave out any instances of "strings".

How can I do this?

Edit: I do want to find instances that are followed by other characters. I literally just need to leave out the ones that end in 's'

Upvotes: 0

Views: 2153

Answers (3)

fronthem
fronthem

Reputation: 4139

If you use a general grep you can done it in this way

echo "stringsMystring1string2strings" | grep -Eo 'strings?' | grep -Eo '^string$'

The idea is you just list all strings by using both pattern string and strings first, by

command:

`grep -Eo 'strings?'`

results:

strings
string
string
strings

The grep the result again by

command:

grep -Eo '^string$'

result:

string
string

And according to regex-lookahead-for-not-followed-by-in-grep, some people suggest to use GNU grep where you can use an option -P or --perl-regexp to enable lookaround feature. A given regex might take form like this

echo "stringsMystring1string2strings" | grep -P 'string(?!s)'

Upvotes: 1

Quinn
Quinn

Reputation: 4504

You can use \b to match a word boundary. Hope this helps:

[root@rh57quinn ~]# echo 'find instances of a particular string - any "string", but leave out "strings" and drawstring' |grep -Eo '\bstring\b'
string
string

Upvotes: 1

anubhava
anubhava

Reputation: 785136

You can use word boundaries in grep:

grep '\<string\>' file

Examples:

# with word boundaries
grep '\<string\>' <<< $'string\nstrings'
string

# without word boundaries
grep 'string' <<< $'string\nstrings'
string
strings

EDIT: Based on comments below you can use:

grep -E '\<string([^s]|$)' file

Example:

grep -E '\<string([^s]|$)' <<< $'string\nstrings'
string

Upvotes: 3

Related Questions