Sunday, October 30, 2022

[SOLVED] Check if line exists in a file

Issue

The problem is that my app tries to add a line to an existing xml file in /system/csc.

I need a function to check if inside the file there is X line and if it is in there the line shouldn't be added also it has to put the line before another line that is present in the file.


Solution

You can check whether the line already exist with grep and use sed to insert it if not:

grep -Fxq "foobar line" file || sed -i '/^context line$/i foobar line' file

This will insert the line foobar line before the line context line if foobar line isn't already found in the file.

Alternately you could do it all with sed:

sed -i '/^foobar line$/d;/^context line$/i foobar line' file


Answered By - Chris Seymour
Answer Checked By - Robin (WPSolving Admin)