Add a line to the file section if it doesn't exist
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 this file, but only if that directory is not already listed. Here's the catch: the directory in question must come from the $ SOME_PATH variable.
I was thinking about using the patch utility, but for that I would have to generate the patch file dynamically to add "+ $ SOME_PATH". Another problem is that I don't know "after context" or line number "% ldirs", so creating a patch file is problematic.
Is there any other option?
Subtle 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
The final answer is thanks to the triple:
fgrep -xq "$SOME_PATH" /path/to/file || sed -i "/%ldirs/ a\\$SOME_PATH" /path/to/file
source to share
line=$(grep "$SOME_PATH" %ldirs)
if [ $? -eq 1 ]
then
echo "$SOME_PATH" >> %ldirs
fi
something like this should work, it works great for me. I'm sure there are other ways to write this as well.
line=$(grep "$SOME_PATH" /path/to/file)
if [ $? -eq 1 ]
then
sed -i 's/%lsdir/%lsdir\n"$SOME_PATH"/' /path/to/file
fi
must work. It will find% lsdir and replace it with% lsdir (newline) $ SOME_PATH (not sure if quotes on $ SOME_PATH are needed here, sure they are not)
source to share