user299709
user299709

Reputation: 5412

bash: recursively grep and replace string

I'm trying to replace all occurences of a string like <Route component={P} path="p.html" routeName="p" /> in all files with <Route component={L} path="'$variable_to_insert'" routeName="L"\/> in current directory via the following script

VARIABLE_TO_INSERT=5


egrep -lR '<Route component={P} path="p.html" routeName="p" />' . | tr '\n' '\0' | xargs -0 -n1 sed -i '' 's/<Route component={L} path="'$variable_to_insert'" routeName="L"\/>/g'`

where $variable_to_insert is defined earlier in the shell script

Upvotes: 0

Views: 132

Answers (2)

Purag
Purag

Reputation: 17061

You can simplify this a bit by using find:

find . -maxdepth 1 -type f | xargs sed -i "s/<Route component={P} path=\"p.html\" routeName=\"p\" \/>/<Route component={L} path=\"$VARIABLE_TO_INSERT\" routeName=\"L\" \/>/g"
#                                            |                                                      | |                                                                   |
#                                            +-------------------- replace this --------------------+ +---------------------------- with this ----------------------------+

Shell variables only get substituted in double-quoted strings, which is why we're doing sed -i "s/.../.../g".

And note the case of $VARIABLE_TO_INSERT — variable names are case-sensitive.

(-maxdepth 1 only grabs files in the current directory. You can remove it to do a recursive search for files in the current directory and all subdirectories.)

Upvotes: 1

jarodeells
jarodeells

Reputation: 416

Use $VARIABLE_TO_INSERT instead of $variable_to_insert because shell variables are case sensitive.

Also, it looks like you are missing the s///g third forward slash.

Upvotes: 0

Related Questions