Home > Net >  sed regex syntax for multiple searches
sed regex syntax for multiple searches

Time:03-23

I am trying to find and replace a specific string within /etc/ssh/sshd_config.
#PermitRootLogin yes > PermitRootLogin no. However I want to make sure I get almost any version of it (if that makes sense).

ex;

#PermitRootLogin yes
PermitRootLogin yes
#PermitRootLogin no

I am fairly new to bash, linux, unix etc and have really only been learning this stuff for the past 2 weeks so if possible, please explain to me like i'm brand new to linux/unix. Thank you in advance.

So far i've tried 2 thing so far and neither of them seem to do what I need.

sed -E 's/(#|^)PermitRootLogin(yes|no)/PermitRootLogin no/' FILENAME

and

sed -E 's/(#/|^/)PermitRootlogin(yes/|no/)/PermitRootLogin no/' FILENAME

I was expecting all the lines in the example above to be changed to;

PermitRootLogin no
PermitRootLogin no
PermitRootLogin no

CodePudding user response:

This one's just missing a space

sed -E 's/(#|^)PermitRootLogin(yes|no)/PermitRootLogin no/' FILENAME 
# ............................^

I would suggest

sed -E '/PermitRootLogin/ s/.*/PermitRootLogin no/' FILENAME

which means: for any line containing the string "PermitRootLogin", replace the entire line with "PermitRootLogin no"


This one

sed -E 's/(#/|^/)PermitRootlogin(yes/|no/)/PermitRootLogin no/' FILENAME

shows a bit of a misunderstanding of the role of the / character in sed.

/ is not a regex character, it's the delimiter for the s command to separate the regular expression, the replacement text, and the flags. See 3.3 The s Command in the sed manual.

CodePudding user response:

With your shown samples, please try following awk code.

awk '/^#?PermitRootLogin/{print "PermitRootLogin no"}' Input_file

Explanation: Simple explanation would be, checking condition if line starts with #(keeping it optional) followed by PermitRootLogin then using printing PermitRootLogin followed by no as per requirement.

NOTE: In case you want to do inplace save the changes into same Input_file then run following: awk '/^#?PermitRootLogin/{print "PermitRootLogin no""}' Input_file > temp && mv temp Input_file

CodePudding user response:

You may use this sed:

sed -E 's/^#?(PermitRootLogin)  .*/\1 no/' file

PermitRootLogin no
PermitRootLogin no
PermitRootLogin no

Where input file is like this:

cat file

#PermitRootLogin yes
PermitRootLogin yes
#PermitRootLogin no

Explanation:

  • ^: Start
  • #?: Match an optional #
  • (PermitRootLogin) : Match PermitRootLogin and capture in 1st group followed by 1 space
  • .*: Match anything till end of line
  • /\1 no/: Replacement section to put value of capture group #1 followed by space and no

To save change inline into file use:

sed -i.bak -E 's/^#?(PermitRootLogin)  .*/\1 no/' file
  • Related