0

我有以下文件:

1xxxxxxx xxxxx xxxxx
2yyyyyyy yyyyy yyyyy
2yyyyyyy yyyyy yyyyy
1xxxxxxx xxxxx xxxxx
2yyyyyyy yyyyy yyyyy
2yyyyyyy yyyyy yyyyy
1xxxxxxx xxxxx xxxxx
1xxxxxxx xxxxx xxxxx
2yyyyyyy yyyyy yyyyy
2yyyyyyy yyyyy yyyyy

当有两个或多个以“1”开头的连续文件时,我想匹配。

意味着我想得到这些线:

1xxxxxxx xxxxx xxxxx
1xxxxxxx xxxxx xxxxx

我尝试使用 grep 但我认为它只能逐行工作,因此以下内容不起作用:

grep -E $1.*$^1 file.txt
4

2 回答 2

1

这条线可能对你有用:

awk '/^1/{i++;a[i]=$0;next}i>1{for(x=1;x<=i;x++)print a[x]}{i=0;delete a}' file

例子:

kent$  cat fi
1xxxxxxx xxxxx xxxxx
2yyyyyyy yyyyy yyyyy
2yyyyyyy yyyyy yyyyy
1xxxxxxx xxxxx xxxxx
2yyyyyyy yyyyy yyyyy
2yyyyyyy yyyyy yyyyy
1here
1we
1want
2yyyyyyy yyyyy yyyyy
1these
1lines
1too
2yyyyyyy yyyyy yyyyy

kent$  awk '/^1/{i++;a[i]=$0;next}i>1{for(x=1;x<=i;x++)print a[x]}{i=0;delete a}' fi
1here
1we
1want
1these
1lines
1too

解释:

awk 
'/^1/{i++;a[i]=$0;next}          #if line starts with 1, ++i, save it in array a, read next line
i>1{for(x=1;x<=i;x++)print a[x]} #if till here, line doesn't start with 1. if i>1, it means, there are atleast 2 consecutive lines starting with 1, in array a. print them out
{i=0;delete a}                   #finally clear i and array a
于 2013-07-05T10:57:00.310 回答
0
perl -lne 'print "$p\n$_" if(/^1xxxxxx/ and $p=~/^1xxxxxx/);$p=$_;' your_file

测试如下:

> cat temp
1xxxxxxx xxxxx xxxxx
2yyyyyyy yyyyy yyyyy
2yyyyyyy yyyyy yyyyy
1xxxxxxx xxxxx xxxxx
2yyyyyyy yyyyy yyyyy
2yyyyyyy yyyyy yyyyy
1xxxxxxx xxxxx xxxxx
1xxxxxxx xxxxx xxxxx
2yyyyyyy yyyyy yyyyy
2yyyyyyy yyyyy yyyyy
> perl -lne 'print "$p\n$_" if(/^1xxxxxx/ and $p=~/^1xxxxxx/);$p=$_;' temp
1xxxxxxx xxxxx xxxxx
1xxxxxxx xxxxx xxxxx
>
于 2013-07-05T12:22:16.337 回答