2

I need to make a change in the php.ini configuration file via sed (or similar).

I need to add the following text:

extension=solr.so

The line has to be added as line number 941 in the configuration file. However, if the file is already there, it should not be added again.

I guess there are two approaches: 1) replace line 941 with the text, or 2) search for the text and add it to line 941 if there are not matches.

I have the following command that works fine, except that the line is added again if the script is run again:

sed '941i\
extension=solr.so' /etc/php5/apache2/php.ini > /etc/php5/apache2/php.ini

How can I make sure that this command does not add the line if it is already there?

phidah
  • 5,794
  • 6
  • 37
  • 58
  • Does this answer your question? [Appending a line to a file only if it does not already exist](https://stackoverflow.com/questions/3557037/appending-a-line-to-a-file-only-if-it-does-not-already-exist) – tripleee May 10 '21 at 07:46

1 Answers1

13

The easiest way would be to test before using grep, for example:

grep -q -e 'extension=solr.so' file || sed '...'

Also, it is estrange that you need exactly that line. You should add it at the end, or something like that.

Also, note that taking the same file as input and output never should be done. This can damage the file badly. You should be using the -i sed parameter to do in-place editing.

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87