问题
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
回答1:
line=$(grep "$SOME_PATH" %ldirs)
if [ $? -eq 1 ]
then
echo "$SOME_PATH" >> %ldirs
fi
something like this should work, it worked fine for me. I'm sure there are other ways to write it, too.
line=$(grep "$SOME_PATH" /path/to/file)
if [ $? -eq 1 ]
then
sed -i 's/%lsdir/%lsdir\n"$SOME_PATH"/' /path/to/file
fi
should work. It'll find %lsdir and replace it with %lsdir(newline)$SOME_PATH (not sure if quotes are needed on $SOME_PATH here, pretty sure they aren't)
来源:https://stackoverflow.com/questions/9118553/add-a-line-to-a-file-section-unless-it-exists