gpt4 book ai didi

regex - 从 shell 编辑一行配置文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:26:27 26 4
gpt4 key购买 nike

给定一个配置文件,比如sshd_config:

[...]
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10
[...]

我想编写一个命令来设置配置设置。例如,我想将 PasswordAuthentication 设置为 no。如果条目已经存在,我想替换它,如果不存在,我想在文件末尾添加它。

我如何从 shell 执行此操作?

最佳答案

您可以使用 awk 来做到这一点。这是我写的脚本:

$ cat setProp.sh
#!/bin/sh

propFile=$1
key=$2
value=$3

awk -v "key=$key" -v "value=$value" '{
if($1==key) {
found=1
print $1" "value
} else {
print
}
}
END {
if(!found) print key" "value
}' $propFile

用法:

$ setProp.sh myfile RhostsRSAAuthentication no
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes
X11Forwarding yes
X11DisplayOffset 10

关于regex - 从 shell 编辑一行配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11721177/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com