Home > Software engineering >  Plus quantifier not working as expected using regex for substitution in sed
Plus quantifier not working as expected using regex for substitution in sed

Time:11-14

The input is #PermitRootLogin no. Why doesn't the following sed expression work with sed?

echo "#PermitRootLogin no" | sed 's/^#PermitRootLogin\s .*/PermitRootLogin yes/'

but after I remove the after the keyword it works?

echo "#PermitRootLogin no" | sed 's/^#PermitRootLogin\s.*/PermitRootLogin yes/'

I thought the after a \s would mean one or more of the previous token.

sed gist

PS: Works either way with regex101.com

CodePudding user response:

You have to escape the sign:

In GNU sed, with basic regular expression syntax these characters ?, , parentheses, braces ({}), and | do not have special meaning unless prefixed with a backslash \.

The plus sign in your case means match a literal , so it would match the plus in #PermitRootLogin no. You have to escape it in \s\ to be able to match one or more whitespace character #PermitRootLogin no

echo "#PermitRootLogin no" | sed 's/^#PermitRootLogin\s\ .*/PermitRootLogin yes/'

Output:

PermitRootLogin yes
  • Related