Prosto Trader
Prosto Trader

Reputation: 3527

Use sed with regex and (

I have a function in php file:

_t('', 'Award received')

I've made a regex, which finds first part of the function _t(''

See Regex in action

Now, I want to replace that function with something else (actually, I want to add argument to the function).

From console:

grep -rl "_t('', 'Award received')" application | xargs sed -i "s/_t\s*\(\s*['|\"](\s*\s*)['|\"]/test/g"

Sed doesn't want to make replacement, it says: "( or ( without a pair", so it looks like it is trying to look for bracket inside regex...

How can I use sed with regex expressions containing brackets?

EDIT: I have test string which I want to replace:

_t('124', 'Test')

When I make simple replacement

sed -i -E 's/124JHGJH/124/g'

it works fine.

But if I try to replace whole string, with parenthesis and other, it just hangs out and not responding...

sed -i -E 's/_t\(\'124JHGJH\'/124/g'

Upvotes: 2

Views: 398

Answers (2)

repzero
repzero

Reputation: 8412

using markers in sed with the regular expression argument

sed -r 's/(_t[^)]+)(\))/\1,new_parameter\2/g'

`(_t[^)]+)` #matches _t and all characters before the last parenthesis. Mark this pattern

(\)) #matches the last parenthesis and mark this pattern

\1,new_parameter\2/ #substitute the first marked pattern, then place the new parameter followed by the second pattern marked, which the the last parenthesis

example

echo "_t('', 'Award received')"|sed -r 's/(_t[^)]+)(\))/\1,new_parameter\2/g'

output

_t('', 'Award received',new_parameter)

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246877

Take note of the difference between \( and ( in sed regex.

To add a new parameter at then end of the function call:

echo "_t('', 'Award received')" | sed 's/_t([^)]\+/&, new_param/'
_t('', 'Award received', new_param)

The regex is:

  • -t( = literal characters
  • [^)]\+ = one or more non-) characters

The next character will be the function's close paren, so that's where I assume you want to insert the new parameter. I use & in the replacement to put the text matched by the regex in its place.

This will break if there's a literal sting argument that contains a close paren character.

Upvotes: 2

Related Questions