1

给定这个输入文件:

SectionMarker and some random text here
this is the text in section 1 
this is the text in section 1
this is the text in section 1
etc
SectionMarker and some random text here also
this is the text in section 2 
this is the text in section 2
this is the text in section 2
etc
SectionMarker and some random text too
this is the text in section 3 
this is the text in section 3
this is the text in section 3
etc

如何使用 awk 或 sed 或其他方法将此文件拆分为几部分?

这是我尝试过的,但没有奏效:

awk -vRS='\SectionMarker[:print:]\n' 'NR==1 {print}' ./data.log 
4

2 回答 2

0

这个单线应该可以完成这项工作:

 awk '{x+=($0~/^SectionMarker/)?1:0}x<2' data.log

测试

kent$  cat data.log
SectionMarker and some random text here
this is the text in section 1 
this is the text in section 1
this is the text in section 1
etc
SectionMarker and some random text here also
this is the text in section 2 
this is the text in section 2
this is the text in section 2
etc
SectionMarker and some random text too
this is the text in section 3 
this is the text in section 3
this is the text in section 3
etc

kent$  awk '{x+=($0~/^SectionMarker/)?1:0}x<2' data.log
SectionMarker and some random text here
this is the text in section 1 
this is the text in section 1
this is the text in section 1
etc

我不知道你想抓住你真正问题的多少部分。你可以放在exit;那个在线网站上,让 awk 不处理整个文件。

于 2012-07-27T22:16:16.690 回答
0

这是使用awk和读取分隔符的一种方式。我添加了一个名为 的额外变量var,它可用于轻松选择所需的“部分”。例如,当 时var=2,将打印第 2 节。IE:

awk -v var=2 -v RS='SectionMarker[^\n]*' -v FS='\n' 'NR == var + 1 { for (i=2; i<NF; i++) print $i }' file.txt

印刷:

this is the text in section 2 
this is the text in section 2
this is the text in section 2
etc

高温高压

于 2012-07-28T03:33:08.577 回答