如何在正则表达式中匹配两个新行 () 而不是一个?



我有一个文本文件,这是一个包含超过80,000个单词的字典,我需要以某种方式解析它,但首先我需要对其进行整理,以便以后可以轻松解析它。正则表达式中有没有办法匹配两个新行而不是一个?即搜索整个文件以查找两个新行而不是一个新行?因为字典中的每个新单词后面都有两行新行。

整个文件的文本格式如下所示:

English : Pyramid of the Cerebellum
Section: Medical
Translation: ...
Description: ...

English: Pyramid
Section: General
Translation: ...
Description: ...

如您所见,每个单词后有 2 个新行,所以我想找到所有大于 2 的新行......然后使用 AWK 替换它,可能吗?

我希望输出是这样的:

English : Pyramid of the Cerebellum
Section: Medical
Translation: ...
Description: ...
English: Pyramid
Section: General
Translation: ...
Description: ...

一个非常快速的方法是使用 awk

awk 'BEGIN{RS="";ORS="nn"}1' /path/to/your/file > /path/to/new/file

这是如何工作的:

awk 知道概念记录(默认为行(,您可以通过其记录分隔符RS定义记录。如果将RS的值设置为空字符串,它将匹配任何大量空行作为记录分隔符。值ORS是输出记录分隔符。它指出应在两个连续记录之间打印哪个分隔符。这设置为两个<换行符>字符。最后,语句1{print $0}的简写,它打印当前记录,后跟输出记录分隔符ORS

你能试试下面的吗?

awk '!/^$/{flag=""} /^$/{flag++} flag==2 && /^$/{next} 1'  Input_file

说明现在也为上述代码添加说明。

awk '
!/^$/{              ##Checking if a line is NOT starting with blank space if yes then do following.
flag=""           ##Nullifying value of variable flag here.
}                   ##Closing this blosk condition here.
/^$/{               ##Checking if a line starts with a blank line then do following.
flag++            ##Incrementing value of variable flag with 1 here.
}                   ##Closing this bock condition here.
flag==2 && /^$/{    ##Checking condition here if variable flag value is 2 and line is empty then do following.
next              ##next keyword is out of the box keyword for awk and will skip all further statements from here.
}                   ##Closing this block condition here.
1                   ##By mentioning 1 printing edited/non-edited line here.
' Input_file        ##Mentioning Input_file name here.

您可以使用以下awk命令:

awk '!NF&&!n{print;n=1}NF{print;n=0}' your_text_file

相关内容

最新更新