Skip to content
Advertisement

Using grep to match where two tokens occur on the same line

I am reading the man page, and found this blog post, and both seem to say the same thing, but it does not work.

I have a project where I need to batch replace lines like

import Foo from '/modules/foo/client/components/Foo.jsx';

into

import Foo from '/modules/foo/client/imports/Foo.jsx';

but I do not want to match lines like :

import Base from '/client/components/Base.jsx';

i.e. : only “imports” from the base dir /modules.

I have tried

$ grep -R "modules.+components" modules/

but no match is found.

Any help with this would be appreciated. Thanks!

Advertisement

Answer

By default, grep interprets the pattern as a basic regular expression (BRE) (not extended -E) and treats some regex metacharacters literally. So + doesn’t have special meaning in your current approach.

Any meta-character with special meaning may be quoted by preceding it with a backslash.

grep -R "modules.+components" modules/

https://www.gnu.org/software/grep/manual/grep.html#index-grep-programs


About BRE: https://www.regular-expressions.info/posix.html#bre

Advertisement