【发布时间】:2021-06-07 00:09:54
【问题描述】:
我有 3000 到 5000 行的文本文件列表,我将其称为编号章节标题。我想删除标题正下方没有文字(句子)的行。
喜欢:
Chapter 1
Chapter 2
Chapter 3
Hello world
Chapter 4
Chapter 5
I love you.
Chapter 6
how many times do I have to do this
chapter 7
Chapter 8
Chapter 9
Some lines have some numbers, numbers and text.
some chapter text has multiple lines.
I thought the best method is to
look for a chapter header line
that has a chapter header line
immediately below it. The last chapter
line becomes an issue if it does
not have any text.
Chapter 10
我想删除第 1、2、4、7、8 和 10 章的行
如果以下行也是使用正向前瞻的章节行,我尝试与 grep 和 sed 匹配章节行(前瞻不会被删除)
grep -Pz '(?s)Chapter\s[\d]{4}\n(?=(Chapter\s[\d]{4}\n)) filename.txt
或在 sed 中(我不理解带有 sed 的脚本)...
sed 's/(?s)Chapter\s[\d]{4}\n(?=(Chapter\s[\d]{4}\n))/ /g' filename.txt
Grep 不能很好地处理多行(如果你使用 -Pz 标签,一切都变成一行。如果一切都是一行,那么任何匹配的任何地方都意味着该行是匹配的。
我也尝试过使用 sed 进行预读,所以我不能使用预读,因为匹配的一行的一部分。
我知道我可以使用 python 或其他脚本语言来做到这一点,但与 bash 命令相比它太慢了。与 python 相比,我能够非常快速地从更大的混乱处理到这个级别,所以我希望我可以只使用 bash 命令来完成这最后一步,并使我们的更新窗口更短。这些文件很大,在有文本的章节中有更多的随机文本。可以是多个句子。
干杯,感谢您的帮助!
【问题讨论】: