简体   繁体   English

使用SED命令添加文件之前,请检查文件中是否存在换行

[英]Check the existence of new line in a file before add using SED command

I have one small doubt regarding sed command. 我对sed命令有一个小疑问。 For example, I have a file like below. 例如,我有一个如下文件。

iptable.save iptable.save

-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT

So next time before adding same line to file , here need a check that whether the new line which we are going to enter is present or not in the file. 因此,下次在将同一行添加到文件之前,需要检查文件中是否存在要输入的新行。 If present, don't do anything, else enter the new line to the file. 如果存在,则什么也不做,否则在文件中输入新行。 Thanks In Advance. 提前致谢。

I would rather use grep for this purpose: 我宁愿为此使用grep

if [ $(grep -cx "$line" iptables.save) -eq 0 ]; then
    echo "$line" >> iptables.save  # Append to the file
fi

-xc means that we want to count the number of lines that are exactly the same as $line . -xc表示我们要计算与$line完全相同的$line

But if you really prefer to use sed : 但是,如果您真的更喜欢使用sed

if [ $(sed -n '/^'"$line"'$/p' iptables.save | wc -l) -eq 0 ]; then
    echo "$line" >> iptables.save  # Append to the file
fi

如果我理解正确,这是awk的工作:

awk -v line="$line" '$0==line{f=1} END{if (!f) print line}' file >> file

This may also help. 这也可能会有所帮助。 Example, checking the file /etc/ssh/sshd_config, if it does not end in an empty line, add one, if it does end with an empty line, do nothing 例如,检查文件/ etc / ssh / sshd_config,如果文件未以空行结尾,则添加一个,如果文件以空行结尾,则不执行任何操作

if [[ $(tail -n 1 /etc/ssh/sshd_config) != "" ]]; then echo "" >> /etc/ssh/sshd_config; fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM