【发布时间】:2019-01-20 15:51:49
【问题描述】:
我想替换或追加配置文件,如 sshd_config:
Key1 value
#Key2 value
命令的思路是:
$ cmd Key1 home file
$ cmd Key2 house file
$ cmd Key3 flat file
所以生成的文件是:
Key1 home
Key2 house
Key3 flat
我们非常欢迎任何帮助。
我以this 为例,但是 cmets 和 uncmets 不能正常工作。
除了我已经使用其他选项进行了管理,但仅适用于 cmets 或未注释的行,如果可能的话,我希望所有内容都在一个命令中。
sed '/^Key\s/{h;s/\(\s\).*/\1newvalue/};${x;/^$/{s//Key newvalue/;H};x}' file
如果密钥存在,则获取,但是,如果不存在,我该如何追加=
sed -i 's/^#\(Key\s\).*/\1newvalue/g' file
非常感谢。我试图理解 sed,但不同的空间非常复杂,我不知道如何使用 # 或不使用。
编辑:使用 -i inplace 的标准输出输出
$ sudo tee -a /usr/local/bin/conf-space-replace-or-append > /dev/null << 'EOL'
#!/bin/bash
awk -i inplace -v key="$1" -v val="$2" '
($1 == key) || ($1 == "#"key) { $0 = key OFS val; done=1 }
{ print }
END { if (!done) print key, val }
' "$3" > /dev/null
EOL
$ sudo chmod +x /usr/local/bin/conf-space-replace-or-append
$ sudo conf-space-replace-or-append Port 22 /etc/ssh/sshd_config
【问题讨论】: