匹配具有相同开头的连续行

时间:2013-07-05 10:42:42

标签: shell awk grep

我有以下文件:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
>