Add a line to a file section unless it exists

泄露秘密 提交于 2019-12-24 14:31:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!