[英]Search string and add string at end of line but before quotes using sed
[英]Check the existence of new line in a file before add using SED command
我對sed命令有一個小疑問。 例如,我有一個如下文件。
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
因此,下次在將同一行添加到文件之前,需要檢查文件中是否存在要輸入的新行。 如果存在,則什么也不做,否則在文件中輸入新行。 提前致謝。
我寧願為此使用grep
:
if [ $(grep -cx "$line" iptables.save) -eq 0 ]; then
echo "$line" >> iptables.save # Append to the file
fi
-xc
表示我們要計算與$line
完全相同的$line
。
但是,如果您真的更喜歡使用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
這也可能會有所幫助。 例如,檢查文件/ 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.