![](/img/trans.png)
[英]Using sed to match a pattern and deleting from the line to the end of the file
[英]Bash - Deleting a line from file using sed
可能很簡單,但是我對bash還是很陌生,我正試圖從包含特定字符串的.txt文件中刪除一行。 該字符串被指定為變量“ $ logline”
我的sed代碼目前是:
logline="example2"
sed -i "/$logline/d" > /root/file.txt
/root/file.txt
文件的內容是...
/root/Dir/example.txt
/root/Dir2/example2.txt
/root/Dir/example3.html
...
我希望僅刪除/root/Dir2/example2.txt
行。
但是,當我運行此命令時,整個txt文件都會被擦除,並且我收到錯誤消息sed: no input files
。
知道我在這里缺少什么嗎?
謝謝
sed -i
沒有輸出,因此當您重定向到文件時,它將被截斷。
而是直接給文件名sed而不重定向:
sed -i "/$logline/d" /root/file.txt
如果變量$logline
包含要匹配的確切文本 ,則sed可能是錯誤的程序。 模式地址是正則表達式,您需要轉義基本RE中可理解的任何元字符,包括\\
, *
和.
。
要刪除固定的字符串,您可能會發現使用grep -Fv
更容易; 就像是
grep -Fv -- "$logline" <"$file" >"$file.new"; mv "$file.new" "$file"
如果確實必須使用sed,則應該選擇是使用-i
就地編輯還是使用標准輸出-不會兩者兼而有之。 所以要么
sed -i "/$logline/d" "$file"
sed "/$logline/d" "$file" >"$file.new" && mv "$file.new" "$file"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.