![如何使用 grep 删除多行字符串](https://linux22.com/image/1031064/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%20grep%20%E5%88%A0%E9%99%A4%E5%A4%9A%E8%A1%8C%E5%AD%97%E7%AC%A6%E4%B8%B2.png)
假设我有file.txt
以下内容(例如简化的。实际上它要复杂得多):
This line I DON'T want to remove \
common substring
This line I want to remove \
common substring
我试过
mv file.txt __file.txt
grep -vwE "This line I want" __file.txt > file.txt
rm __file.txt
重新创建file.txt
并删除整个'This line I want to remove common substring'
与线闸,但作为输出我得到
This line I DON'T want to remove \
common substring
common substring
我不能grep -vwE "common substring" __file.txt > file.txt
另外使用因为它会影响另一个多行字符串......
那么如何让 grep 在考虑行中断的情况下删除整个多行?
答案1
应删除分成 8 行的行
如果每个“段落”之间有一个空行,那么你可以写
awk -F '\n' -v RS= -v ORS='\n\n' 'NF != 8'
演示:
cat <<"END" | awk -F'\n' -v RS= -v ORS='\n\n' 'NF != 8'
This line I DON'T want to remove \
common substring
This line I want to remove \
common substring \
3 \
4 \
5 \
6 \
7 \
8
Last line
END
This line I DON'T want to remove \
common substring
Last line
请注意,内置的 bashread
可以遵循行连续性,但它们的位置被抹去了:
while IFS= read line; do declare -p line; done << "END"
This line I DON'T want to remove \
common substring
This line I want to remove \
common substring \
3 \
4 \
5 \
6 \
7 \
8
Last line
END
declare -- line="This line I DON'T want to remove common substring"
declare -- line=""
declare -- line="This line I want to remove common substring 3 4 5 6 7 8"
declare -- line=""
declare -- line="Last line"