3

New to sed, so please bear with me...

I have a php file which contains the following line:

define('TARGET_A','044');

Id like to find that line and replace it with the following using sed:

define('TARGET_K','076');

I have tried:

$ sed -i 's/define\(\'TARGET_A\',\'044\'\)\;/define\(\'TARGET_K\',\'076\'\)\;/' myfile.php

I have tried SEVERAL variations, tried escaping the parens and removing the semicolon, nothing seems to work

ANY help at all GREATLY appreciated, thanks

dsrupt
  • 55
  • 7

3 Answers3

5

That's a lot of escaping. How about... no escaping at all?

sed -i '.bak' "s/define('TARGET_A','044');/define('TARGET_K','076');/" myfile.php

Example:

cternus@astarael:~⟫ cat myfile.php
define('TARGET_A','044');
cternus@astarael:~⟫ sed -i '.bak' "s/define('TARGET_A','044');/define('TARGET_K','076');/"  myfile.php
cternus@astarael:~⟫ cat myfile.php
define('TARGET_K','076');
Christian Ternus
  • 8,406
  • 24
  • 39
  • THANK YOU SINCERELY for this FAST answer! I can't even accept it yet you answered so quickly! hah! you ROCK. This worked! – dsrupt Aug 25 '16 at 22:55
  • heres a tougher question... Is there a way to auto increment the number? with or without that leading 0 present? – dsrupt Aug 25 '16 at 23:10
  • 1
    @dsrupt no, that can't be done with sed but it would be trivial if you were using awk instead of sed. That's really a very different requirement though so post a follow up question with concise, testable sample input and expected output and this time show your target line(s) in context. – Ed Morton Aug 25 '16 at 23:14
1

This worked for me:

$sed -i "s/define('TARGET_A','044');/define('TARGET_K','076');/" myfile.php

I changed the argument string delimiter to make it simpler.

0

You can't escape 's in a '-delimited script so you need to escape back to shell with '\'' whenever you need a '. You might be tempted to use " to delimit the script instead but then you're opening it up to shell variable expansion, etc. so you need to be careful about what goes in your script and escape some characters to stop the shell from expanding them. It's much more robust (and generally makes your scripts simpler) to just stick to single quotes and escape back to shell just for the parts you NEED to:

$ sed 's/define('\''TARGET_A'\'','\''044'\'');/define('\''TARGET_K'\'','\''076'\'');/' file
define('TARGET_K','076');
Ed Morton
  • 188,023
  • 17
  • 78
  • 185