rahul mukherjee
rahul mukherjee

Reputation: 77

Grep to find a pattern and replace in same line

I have a project directory with folders containing .html files. I want to find those files which have the pattern -

'btn-primary.*{.*Save'

And replace the

'btn-primary' word with 'btn-primary Save' 

only in those lines.

What I have done:

grep -rl -e 'btn-primary.*{Save' . |xargs sed -i 's/btn-primary/btn-primary Save/g'

What this did:

This found all files that have that pattern, that's okay. Then, sed ran on all of those files and replaced 'btn-primary' with 'btn-primary save' wherever it got - which is not what I want

What I want: to replace on those lines where there is 'Save' somewhere after 'btn-primary'.

Any help will be very much appreciated.

Regards, Rahul

Upvotes: 0

Views: 538

Answers (1)

William Pursell
William Pursell

Reputation: 212158

Why are you using grep at all? Sed does pattern matching:

sed -e 's/btn-primary\(.*{.*Save\)/btn-primary Save\1/g'

or:

sed -e 's/\(btn-primary\)\(.*{.*Save\)/\1 Save\2/g'

If you are using grep to try to trim down the number of files that sed will operate on, you're fooling yourself if you believe that is more efficient. By doing that, you will read every file that doesn't match only once, but every file that does match will be read twice. If you only use sed, every file will be read only once.

Upvotes: 3

Related Questions