SecurityAmoeba SecurityAmoeba - 1 year ago 94
Linux Question

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

Answer Source

Let's break down the regexp:

  • ^ 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download