I have a file that looks like this:
...
%ldirs
(list of line-separated directories)
...
With a shell script, I need to add a directory to the list in that file, but only if that directory is not already in the list. Here's the catch: The directory in question must come from a variable $SOME_PATH.
I thought about using the patch utility, but to do that I would have to generate the patch file dynamically to add "+$SOME_PATH". The other problem is that I do not know the "after context" or the line number of "%ldirs", so generating the patch file is problematic.
Is there another option?
Tweaked answer - Thanks to Rob:
line=$(grep "$SOME_PATH" /path/to/file)
if [ $? -eq 1 ]
then
sed -i "/%ldirs/ a\\$SOME_PATH" /path/to/file
fi
Final answer - Thanks to tripleee:
fgrep -xq "$SOME_PATH" /path/to/file || sed -i "/%ldirs/ a\\$SOME_PATH" /path/to/file