从txt文件中提取文本

vwoqyblh  于 2022-10-23  发布在  Linux
关注(0)|答案(2)|浏览(364)

我有一个txt文件,上面有唱片。记录遵循以下模式:
six lines, blank space, six lines,.如下例:

string line 1
string line 2
string line 3
string line 4
string line 5 (year format yyyy)
string line 6 (can use several lines)
<blank space> (always a blank space when a new txt block begins)
string line 1
string line 2
string line 3
string line 4
string line 5 (year format yyyy)
string line 6

下面是一个恰当的例子:我需要标题(第2行)和年份(第5行)

Hualong Yu, Geoffrey I. Webb,
Adaptive online extreme learning machine by regulating forgetting factor by concept drift map,
Neurocomputing,
Volume 343,
2019,
Pages 141-153,
ISSN 0925-2312,
https://doi.org/10.1016/j.neucom.2018.11.098.
https://www.sciencedirect.com/science/article/pii/S0925231219301572

Antonino Feitosa Neto, Anne M.P. Canuto,
EOCD: An ensemble optimization approach for concept drift applications,
Information Sciences,
Volume 561,
2021,
Pages 81-100,
ISSN 0020-0255,
https://doi.org/10.1016/j.ins.2021.01.051.
https://www.sciencedirect.com/science/article/pii/S002002552100089X

我想提取第2行中的字符串和第5行中的年份所有文本块(由空格分隔),将其保存到另一个txt文件中,输出如下:

string line2 , yyyy

我没有Linux外壳的经验,所以我在这里请求一些输入来帮助我完成这项任务。
谢谢

qnzebej0

qnzebej01#

如果您不关心第5行中尾随的逗号,只需执行以下操作:

awk '{print $2, $5}' RS= FS='\\n' input > output

这假设分隔记录的空行确实是完全空白的,并且不包含任何空格。如果该行中有任何空格,则需要对数据进行预筛选以将其删除。
例如:

$ cat input
Hualong Yu, Geoffrey I. Webb,
Adaptive online extreme learning machine by regulating forgetting factor by concept drift map,
Neurocomputing,
Volume 343,
2019,
Pages 141-153,
ISSN 0925-2312,
https://doi.org/10.1016/j.neucom.2018.11.098.
https://www.sciencedirect.com/science/article/pii/S0925231219301572

Antonino Feitosa Neto, Anne M.P. Canuto,
EOCD: An ensemble optimization approach for concept drift applications,
Information Sciences,
Volume 561,
2021,
Pages 81-100,
ISSN 0020-0255,
https://doi.org/10.1016/j.ins.2021.01.051.
https://www.sciencedirect.com/science/article/pii/S002002552100089
$ awk '{print $2, $5}' RS= FS='\\n' input
Adaptive online extreme learning machine by regulating forgetting factor by concept drift map, 2019,
EOCD: An ensemble optimization approach for concept drift applications, 2021,
tv6aics1

tv6aics12#

类似于:

perl -00 -nE 'my @ln = (split /,\n/)[1,4]; say join(",", @ln)'  input.txt > output.txt

至少应该作为一个起点。一次阅读一个段落,拆分成行,并将您要查找的两个内容打印在由逗号分隔的同一行中。

相关问题