更清洁的方式来写入多个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_configIs 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_configSince 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_configIf 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更多推荐
发布评论