3

I am trying to build a small sh script that does a basic find / replace but with a small twist, that I wonder if I am going about it the wrong way.

here is the old string

mysql_fetch_array($foo)

here is what i need

$foo->fetch_array()

now the easy part is:

find . -type f -name "*.php" -exec sed -i'' -e 's/mysql_fetch_array(/->fetch_array(/g' {} +

But I don't know how to pull $foo from the parantheses, and then shove it up in front ... Do I do this in the same sed regex .. Do I store it in a variable and reconstruct it? What's the most efficient way to go about this?

I have tried multiple things, but I am having trouble with escaping the $ etc etc ... My mind is thoroughly exhausted!

EDIT

It should be noted that I was needing to match mysql_fetch_array specifically as well -- my bad for not specifying it in the OP

4
find . -type f -name "*.php" -exec sed -i -e 's/^.*mysql_fetch_array(\$\([^)]*\))/$\1->fetch_array()/' {} \;
  • Ahh! I see! Use regex first to isolate and then reconstruct it ... clever! – Zak Feb 17 '17 at 21:45
  • Yeah. Matching the regex meta characters - '$' and '()' here - is so often a pain. If the replacement is simple enough, just ignoring them in the match and including them 'manually' in the replacement is easier. – Eli Heady Feb 17 '17 at 21:50
  • question ... Just tested with blah_blah_blah($something) and it replaced it --- Is there a way to get it to look specifically for mysql_fetch_array? There are other like queries that I don't want it to touch. – Zak Feb 17 '17 at 21:56
  • Changed in edit. Add the specific string you want to match before the first paren. – Eli Heady Feb 17 '17 at 21:57
  • Great, I edited my OP as well to denote that I was slightly unclear -- Thanks for you great solution and explanation! – Zak Feb 17 '17 at 22:03
0

Use this:

find . -type f -name "*.php" -exec sed -i'' -e 's/mysql_fetch_array(\$foo)/\$foo->fetch_array\(\)/g' {} +

Use \ to escape $ character, and in new value for replacement, parenthesis must be escaped too.

So, you need to use \ for ( and )

  • I think 'variable_here' was a placeholder – Eli Heady Feb 17 '17 at 21:44
  • yes '$variable_here' is a placeholder hence the term "reusable string" in the title – Zak Feb 17 '17 at 21:47
  • @EliHeady hmm, I think it's a specific name! If it be a placaholder, your answer is better than me – MrRolling Feb 17 '17 at 21:48
  • @Zak so please use foo or bar for placaholders in your questions :) – MrRolling Feb 17 '17 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.