2

Given a file with the following string:

fastcgi_param WP_ENV staging;

I need an sed expression that will replace the word 'staging' with a new string:

fastcgi_param WP_ENV production;

In the first example the 3rd word is variable. It could be any lowercase string eg development, local, etc.

I tried the following:

sed  's/fastcgi_param WP_ENV [\w+]/fastcgi_param WP_ENV production/g' 

but it does not pick up the work correctly. The regexp for the word does not match.

What would be the correct sed command to do this type of replacement?

5

Add -E and remove the square brackets:

$ sed -E 's/fastcgi_param WP_ENV \w+/fastcgi_param WP_ENV production/g' file
fastcgi_param WP_ENV production;

Notes:

  1. + is not supported in basic regular expressions. -E turns on extended regex which does support +.

  2. \w+ matches one or more word characters. [\w+] matches any one of \, w, or +.

  3. \w is not portable. For POSIX compatibility, use:

    $ sed -E 's/fastcgi_param WP_ENV [[:alnum:]]+/fastcgi_param WP_ENV production/g' file
    fastcgi_param WP_ENV production;
    
  4. You can avoid the double typing of the line by using a capture group:

    $ sed -E 's/(fastcgi_param WP_ENV) [[:alnum:]]+/\1 production/g' file
    fastcgi_param WP_ENV production;
    
2

Do:

sed -E 's/^(([^[:blank:]]+[[:blank:]]+){2})[[:lower:]]+(.*)/\1production\3/'
  • ^(([^[:blank:]]+[[:blank:]]+){2}) matches first two words and put those in captured group so that we can refer the group in the replacement

  • [[:lower:]]+ matches one or more lowercase characters

  • (.*) matches the remaining portion of the line and put in captured group

  • In the replacement we have kept captured group, 1 (first two words with trailing whitespace) and 3 (portion after desired lowercases to be replaced). In between these, the desired replacement string is given.

Example:

% sed -E 's/^(([^[:blank:]]+[[:blank:]]+){2})[[:lower:]]+(.*)/\1production\3/' <<<'fastcgi_param WP_ENV staging;'
fastcgi_param WP_ENV production;

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.