如何从由空行分隔的列中提取行?
How to extract lines from a column separated by empty lines?
我有一大堆标记化的句子。不同的句子之间用空行隔开。输入文件基本上就是一大列。
我想以每个独特的句子都有自己的行的方式转置单列。
输入:
Sentence1
Sentence1
Sentence1
Sentence1
Sentence2
Sentence2
Sentence2
...
SentenceN
期望的输出是这样的:
Sentence1 Sentence1 Sentence1 Sentence1
Sentence2 Sentence2 Sentence2
...
我一直在寻找 grep、awk、sed 和 tr,但我一直在努力寻找正确的语法。
谢谢!
perl
非常简单:
#!/usr/bin/env perl
use strict;
use warnings;
local $/ = "\n\n";
while ( <DATA> ) {
s/\n/ /g;
print;
print "\n";
}
__DATA__
Sentence1
Sentence1
Sentence1
Sentence1
Sentence2
Sentence2
Sentence2
或one-liner-ified:
perl -00 -pe 's/\n/ /g'
awk解决方案
awk '{ if(~"^$") {print a;a="";} else a=a" "[=10=];} END {print a}' test.txt
如果您明智地选择记录和字段分隔符,awk
:
会很简单
awk '=' RS= FS="\n" OFS=" " infile
输出:
Sentence1 Sentence1 Sentence1 Sentence1
Sentence2 Sentence2 Sentence2
...
SentenceN
说明
RS=
将记录分隔符设置为 "empty line".
FS="\n"
将字段分隔符设置为 new-line.
OFS=" "
将输出分隔符设置为 space.
=
重新评估输入并根据 FS
拆分它。这也评估为真,因此输出输入 OFS
作为分隔符。
我有一大堆标记化的句子。不同的句子之间用空行隔开。输入文件基本上就是一大列。
我想以每个独特的句子都有自己的行的方式转置单列。
输入:
Sentence1
Sentence1
Sentence1
Sentence1
Sentence2
Sentence2
Sentence2
...
SentenceN
期望的输出是这样的:
Sentence1 Sentence1 Sentence1 Sentence1
Sentence2 Sentence2 Sentence2
...
我一直在寻找 grep、awk、sed 和 tr,但我一直在努力寻找正确的语法。
谢谢!
perl
非常简单:
#!/usr/bin/env perl
use strict;
use warnings;
local $/ = "\n\n";
while ( <DATA> ) {
s/\n/ /g;
print;
print "\n";
}
__DATA__
Sentence1
Sentence1
Sentence1
Sentence1
Sentence2
Sentence2
Sentence2
或one-liner-ified:
perl -00 -pe 's/\n/ /g'
awk解决方案
awk '{ if(~"^$") {print a;a="";} else a=a" "[=10=];} END {print a}' test.txt
如果您明智地选择记录和字段分隔符,awk
:
awk '=' RS= FS="\n" OFS=" " infile
输出:
Sentence1 Sentence1 Sentence1 Sentence1
Sentence2 Sentence2 Sentence2
...
SentenceN
说明
RS=
将记录分隔符设置为 "empty line".FS="\n"
将字段分隔符设置为 new-line.OFS=" "
将输出分隔符设置为 space.=
重新评估输入并根据FS
拆分它。这也评估为真,因此输出输入OFS
作为分隔符。