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?

2 Answers 2


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;


  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;


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.


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

You must log in to answer this question.

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