Title: How to insert lines into specific files in which a string is not present?
Tags: linux;bash;sed;grep
Question: I'm looking for some help with a small script.
I would like to search all files corresponding to
/usr/local/directadmin/data/users/*/httpd.conf
for the string
centralized.log
If the string is not present in a file, I would like to insert 2 lines into it.
Currently I have the following script:
#!/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 &amp;&amp; sed -i '65iCustomLog /var/log/centralized.log combined' /usr/local/directadmin/data/users/*/httpd.conf
At the moment, if the string is not found in any of the files, the lines are inserted into all of the files, and if the string is found in at least one file, nothing happens. Can I make it so that the lines get added to all files in which the string is not present?

Here is the accepted answer: Use a loop:
#!/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

Here is another answer: With 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

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:08/09/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<linux><bash><sed><grep>', 'Title': 'How to insert lines into specific files in which a string is not present?', 'ViewCount': 47, 'id': 31907605, 'user_AboutMe': None, 'user_AccountId': 6762622.0, 'user_DisplayName': 'wtptrs', 'user_Reputation': 23.0, 'user_Views': 5.0, 'user_id': 5208853.0}}