linux - 编写多个 sed 命令的更简洁的方法?

标签 linux bash shell ubuntu sed

是否有更 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

最佳答案

由于要匹配的模式相似,您可以对 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

关于linux - 编写多个 sed 命令的更简洁的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23369917/

相关文章:

从 bash 脚本运行时出现 Python 语法错误

linux - 管道使用 awk 代码创建的 awk 对象

c - Linux TCP/IP 诊断 C 程序中 TCP/IP read() 返回 0 的原因

linux计数字符然后输出用户输入的字符串中的字符数,它还需要一个while循环

c++ - 如何确保boost安装成功?

bash - 按周数拆分 csv 文件的简单 bash 脚本

ruby - 如何并行运行两种方法ruby

windows - 生成文件/shell : Append text to a name and use that name as a variable

php - linux shell 脚本 : how can I create a service that will run in background?

linux - 在 Makefile 中在 Linux 和 MacOS 上使用 sed