Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed regex syntax for multiple searches

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
like image 730
LastTwinkie Avatar asked Oct 26 '25 07:10

LastTwinkie


1 Answers

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.

like image 55
glenn jackman Avatar answered Oct 28 '25 20:10

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!