SecurityAmoeba
SecurityAmoeba

Reputation: 43

Config modification with sed

Sorry this is a quick one. I am attempting to modify the value of an ssh config file using a simple sed command (as part of a larger script performing a number of functions). I can't seem to figure out why it is not working. Here is the line of the config I am trying to change:

PermitRootLogin without-password

Here is my code:

    sed 's/^\(PermitRootLogin\s*.\s*\).*$/\1Yes/' sshd_config

So the goal is to replace the 'without-password' with yes. It appears to work except I receive this instead:

PermitRootLogin wYes

Upvotes: 2

Views: 1837

Answers (2)

SLePort
SLePort

Reputation: 15461

Try this:

sed 's/^\(PermitRootLogin \).*/\1Yes/' sshd_config

Use the -i option to edit the file in place:

sed -i 's/^\(PermitRootLogin \).*/\1Yes/' sshd_config

Your pattern was capturing w because it's the first character (.) after zero or more space (\s*) in regex \s*.

Upvotes: 3

Barmar
Barmar

Reputation: 781004

Let's break down the regexp:

^\(PermitRootLogin\s*.\s*\).*$
  • ^ matches the beginning of the line
  • \( starts a capture grou
  • PermitRootLogin matches that directive
  • \s* matches the longest sequence of spaces after the directive
  • . matches the first character after the spaces, which is the w at the beginning of without-password
  • \s* matches the longest sequence of spaces after the w. Since there are no spaces there, it matches the empty string.
  • \) ends the capture group

All the above gets put into capture group 1.

  • .* matches everything after that.
  • $ matches the end of the line.

So capture group 1 contains PermitRootLogin w. You then copy that into the replacement, with Yes added to it. The result is

PermitRootLogin wYes

I would just use

sed 's/^PermitRootLogin\s.*$/PermitRootLogin Yes/' sshd_config

There's no need for a capture group when you don't need to copy any variable match to the replacement.

Upvotes: 2

Related Questions