使用前后条件进行基于段落的搜索 UNIX KSH

使用前后条件进行基于段落的搜索 UNIX KSH

我有一个像这样的文件:

<Set of long paragraphs here>
<Set of long paragraphs here>
<Set of long paragraphs here>
After
Address1
Address2
Address3
Before
<Set of long paragraphs here>
<Set of long paragraphs here>
<Set of long paragraphs here>
After
Address1
Address2
Address3
Before
<Set of long paragraphs here>
<Set of long paragraphs here>
<Set of long paragraphs here>
After
Address1
Address2
Address3
Before
<Set of long paragraphs here>
<Set of long paragraphs here>
<Set of long paragraphs here>
After
Address1
Address2
Address3
Before
<Set of long paragraphs here>
<Set of long paragraphs here>
<Set of long paragraphs here>
After
Address1
Address2
Address3
Before
<Set of long paragraphs here>
<Set of long paragraphs here>
<Set of long paragraphs here>

我需要将单词之间的行写入After单独Before的输出文件中。例如,输出文件应如下所示:

Line Number : Address1
Line Number : Address2
Line Number : Address3
......................
......................

我试过这个:

awk '/After/,/Before/' Details.txt>output.txt

但这没有用。我怎样才能做到这一点?

答案1

你可以尝试这样的事情:

$ awk '/After/{a=1;next}/Before/{a=0}; (a==1){print NR" : "$0}' file 
5 : Address1
6 : Address2
7 : Address3
13 : Address1
14 : Address2
15 : Address3
21 : Address1
22 : Address2
23 : Address3
29 : Address1
30 : Address2
31 : Address3
37 : Address1
38 : Address2
39 : Address3

这个想法很简单。a如果当前行与Afteror匹配,则变量会更改值,并且仅当等于 1 时才Before打印该行。a

要将它们保存到单独的输出文件中,您可以执行以下操作:

awk '/After/{a=1; k++;next}/Before/{a=0}; (a==1){print NR" : "$0 > k".out"}' file 

在这里,我使用变量k来计算找到该单词的次数After。输出文件将是k和的当前值.out。如果我在你的例子上运行上面的代码,我会得到:

$ ls
1.out  2.out  3.out  4.out  5.out

相关内容