0

I am wondering if this is possible, I want to mass replace a text in various files, this is not a problem. What i cannot figure out, or even if its possible is to replace the text in a specific manner.

For example:

String = XXXXX_name($var1); 

XXXX is fixed, so XXXX replace with YYYY for example, simple enough. but the more complicated part is:

($var1);

I want to insert another variable, so the match would be ");" <-- insert before this, BUT if the string is already had two variables ($var1,$var2); to not insert anything.

Now to add another thing in, Var1 and Var2 can be called various things, so the match would have to be if $ > 1 inside () then to do nothing, If $ = 1 inside () then to insert ", $var2" before );

String = XXXXX_name($var1);
Should become: String = YYYYY_name($var1, var2);

1 Answer 1

1

Something like this?

$ echo 'String = XXXXX_name($var1); ' | 
    sed -E -e 's/XXXXX_name\((\$[[:alnum:]_]+)\);/YYYYY_name\(\1, \$var2\);/'
String = YYYYY_name($var1, $var2); 

In extended regular expressions, the unquoted parenthesis capture the part within them and sed's \1 puts the captured part back in the replacement part.

7
  • Just put this through a few tests and this could actually work, does exactly as i hoped. This will save me many hours of searching and replacing :) Thank you sir Oct 28, 2021 at 15:22
  • How would you do this the other way a around as well if you dont mind me asking? If you where to insert the variable at the start of the the open bracket? Its okay, i see its switching the end replace around: sed -E -e 's/mssql_((\$[[:alnum:]_]+));/sqlsrv_query(\$var2\, \1);/' Oct 28, 2021 at 15:39
  • @DaveHamilton, mmh, I'm not sure what you mean. \( matches the literal left parentheses, (...) captures the insides (to \1 in the replacement part), \$ matches a literal dollar sign, and [[:alnum:]_] any number of alphanumerics or underscores. And \) matches the right paren. So, edit those as necessary.
    – ilkkachu
    Oct 28, 2021 at 15:43
  • ah, yes, it doesn't matter where in the replacement part you drop the \1.
    – ilkkachu
    Oct 28, 2021 at 15:44
  • is there anything special with this expression as when i pass the -i parameter over to attempt to replace the content in a file, it doesn't replace anything? Oct 29, 2021 at 8:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .