仅当文件不存在时才向文件追加一行 [英] Appending a line to a file only if it does not already exist
本文介绍了仅当文件不存在时才向文件追加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将以下行添加到配置文件的末尾:
I need to add the following line to the end of a config file:
include "/configs/projectname.conf"
到一个名为 lighttpd.conf
我正在考虑使用 sed
来执行此操作,但我不知道如何操作.
I am looking into using sed
to do this, but I can't work out how.
如果该行不存在,我将如何仅插入它?
How would I only insert it if the line doesn't already exist?
推荐答案
保持简单:)
grep + echo 应该足够了:
grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
-q
安静-x
匹配整行-F
模式是一个普通的字符串- https://linux.die.net/man/1/grep
-q
be quiet-x
match the whole line-F
pattern is a plain string- https://linux.die.net/man/1/grep
合并了@cerin 和@thijs-wouters 的建议.
这篇关于仅当文件不存在时才向文件追加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文