更清洁的方式来写入多个sed命令?(Cleaner way to write multiple sed commands?)

编程入门 行业动态 更新时间:2024-10-27 22:31:35
更清洁的方式来写入多个sed命令?(Cleaner way to write multiple sed commands?)

是否有更多的DRY方式来编写下列命令(将它们放入bash shell脚本中):

sudo sed -i 's/^#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config sudo sed -i 's/^#PermitEmptyPasswords yes/PermitEmptyPasswords no/' /etc/ssh/sshd_config sudo sed -i 's/PermitEmptyPasswords yes/PermitEmptyPasswords no/' /etc/ssh/sshd_config sudo sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config sudo sed -i 's/^#X11Forwarding yes/X11Forwarding no/' /etc/ssh/sshd_config sudo sed -i 's/X11Forwarding yes/X11Forwarding no/' /etc/ssh/sshd_config

Is there a more DRY way to write the following commands (will be putting them in a bash shell script):

sudo sed -i 's/^#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config sudo sed -i 's/^#PermitEmptyPasswords yes/PermitEmptyPasswords no/' /etc/ssh/sshd_config sudo sed -i 's/PermitEmptyPasswords yes/PermitEmptyPasswords no/' /etc/ssh/sshd_config sudo sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config sudo sed -i 's/^#X11Forwarding yes/X11Forwarding no/' /etc/ssh/sshd_config sudo sed -i 's/X11Forwarding yes/X11Forwarding no/' /etc/ssh/sshd_config

最满意答案

由于要匹配的模式相似,因此可以使用4个字符串的替代方法并捕获它。 使字符串开头的#为可选。

以下将结合成一个:

sed -i -r 's/^#?(PermitRootLogin|PermitEmptyPasswords|PasswordAuthentication|X11Forwarding) yes/\1 no/' /etc/ssh/sshd_config

如果您的sed版本不支持扩展正则表达式,则可以这样说:

sed -i 's/^#\{0,1\}\(PermitRootLogin\|PermitEmptyPasswords\|PasswordAuthentication\|X11Forwarding\) yes/\1 no/' /etc/ssh/sshd_config

Since the patterns to be matched are similar, you could make use of alternation for the 4 strings and capture it. Make the # at the beginning of the string optional.

The following would combine those into one:

sed -i -r 's/^#?(PermitRootLogin|PermitEmptyPasswords|PasswordAuthentication|X11Forwarding) yes/\1 no/' /etc/ssh/sshd_config

If your version of sed doesn't support extended regular expressions, you could say:

sed -i 's/^#\{0,1\}\(PermitRootLogin\|PermitEmptyPasswords\|PasswordAuthentication\|X11Forwarding\) yes/\1 no/' /etc/ssh/sshd_config

更多推荐

本文发布于:2023-08-01 14:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1360363.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   清洁   命令   方式   multiple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!