Linux 如何在不存在字符串的特定文件中插入行?
我正在寻找一个小脚本的帮助 我想搜索对应于的所有文件Linux 如何在不存在字符串的特定文件中插入行?,linux,bash,sed,grep,Linux,Bash,Sed,Grep,我正在寻找一个小脚本的帮助 我想搜索对应于的所有文件 /usr/local/directadmin/data/users/*/httpd.conf 对于字符串 centralized.log 如果文件中没有字符串,我想在其中插入两行 目前我有以下脚本: #!/bin/bash if ! grep -q centralized.log /usr/local/directadmin/data/users/*/httpd.conf ; then sed -i '33iCustomLog /var/
/usr/local/directadmin/data/users/*/httpd.conf
对于字符串
centralized.log
如果文件中没有字符串,我想在其中插入两行
目前我有以下脚本:
#!/bin/bash
if ! grep -q centralized.log /usr/local/directadmin/data/users/*/httpd.conf ; then
sed -i '33iCustomLog /var/log/centralized.log combined' /usr/local/directadmin/data/users/*/httpd.conf && sed -i '65iCustomLog /var/log/centralized.log combined' /usr/local/directadmin/data/users/*/httpd.conf
fi
此时,如果在任何文件中都找不到该字符串,则会将这些行插入到所有文件中,如果在至少一个文件中找到该字符串,则不会发生任何事情。我可以将行添加到所有不存在字符串的文件中吗?使用循环:
#!/bin/bash
for file in /usr/local/directadmin/data/users/*/httpd.conf ; do
if ! grep -q centralized.log "$file" ; then
sed -i '33iCustomLog /var/log/centralized.log combined' "$file"
sed -i '65iCustomLog /var/log/centralized.log combined' "$file"
fi
done
使用循环:
#!/bin/bash
for file in /usr/local/directadmin/data/users/*/httpd.conf ; do
if ! grep -q centralized.log "$file" ; then
sed -i '33iCustomLog /var/log/centralized.log combined' "$file"
sed -i '65iCustomLog /var/log/centralized.log combined' "$file"
fi
done
使用GNU awk:
awk -v RS='^$' -v ORS= -i inplace '
{ print }
!/centralized\.log/ {
print "33iCustomLog /var/log/centralized.log combined"
print "65iCustomLog /var/log/centralized.log combined"
}
' /usr/local/directadmin/data/users/*/httpd.conf
使用GNU awk:
awk -v RS='^$' -v ORS= -i inplace '
{ print }
!/centralized\.log/ {
print "33iCustomLog /var/log/centralized.log combined"
print "65iCustomLog /var/log/centralized.log combined"
}
' /usr/local/directadmin/data/users/*/httpd.conf