0

Somewhy replace empty chars (space, tab, etc.) is not working with sed and regexp grouping:

sed -i "s|dir(\s*)=(\s*)'${site_path_source}'|dir$1=$2'${site_path_target}'|g"

The whole line does replace a string in a file:

sudo find "${config_path}" -type f -exec sed -i "s|dir(\s*)=(\s*)'${site_path_source}'|dir$1=$2'${site_path_target}'|g" {} \;

Any idea how to fix it?

Thanks!

EDIT1: Now using -r to enable extended regular expressions, but still doesn't replace:

sudo find "${config_path}" -type f -exec sed -ir "s|dir(\s*)=(\s*)'${site_path_source}'|dir$1=$2'${site_path_target}'|g" {} \;

But still doesn't do the replace.

EDIT2 (WORKING SOLUTION): When using \( \) for grouping, it WORKS:

sudo find "${config_path}" -type f -exec sed -i "s|dir\(\s*\)=\(\s*\)'${site_path_source}'|dir\1=\2'${site_path_target}'|g" {} \;

But I don't understand, why the EDIT1 solution with -r extended regular expressions is not working.

EDIT3 (WORKING SOLUTION2): Using -r to enable extended regular expressions, it WORKS NOW:

sudo find "${config_path}" -type f -exec sed -r -i "s|dir(\s*)=(\s*)'${site_path_source}'|dir$1=$2'${site_path_target}'|g" {} \;

Explanation:

  • Using "sed -ir SUFFIX" is wrong, because -i needs a suffix.
  • Using "sed -r -i SUFFIX" is GOOD, because -r and -i are used separately, and -i is followed by a suffix.
2

The command

sed -i "s|dir(\s*)=(\s*)'${site_path_source}'|dir$1=$2'${site_path_target}'|g"

looks for lines containing d i r ( zero or more whitespace ) = ( zero or more whitespace ) ' etc. If you are trying to use grouping you must either use \( \) or say sed -r to enable extended regular expressions.

Note that $1 and $2 are the first two positional parameters; if you want the first and second groups in the matched string you must use \1 and \2.

  • Thanks! I always forget, that sed needs the grouping char to be escaped. Will test the fix today. – klor Jul 7 '17 at 7:56
  • Edited the post. But still no luck. Something is still wrong, no replace done. – klor Jul 7 '17 at 17:10
  • When using escaping the grouping characters works. But if I use -r for extended regular expressions it is not working. Strange. Maybe -i -r options can not be used together? – klor Jul 7 '17 at 17:59
  • Your answer was not a perfect solution, but helped me to find the problem with my sed. So accepting your answer as solution. – klor Jul 7 '17 at 18:17

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.