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

Shell 匹配具有相同开头的连续行,shell,awk,grep,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
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

这一行可能适合您:

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

> 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
>

@Jérémie在回答中看到解释谢谢你的解释。现在我更好地理解了它。我仍然有一个问题:当文件以两行或更多行以“1”开头时,该命令不起作用。我知道这是因为第二个条件在这种情况下不成立,所以最后一个数组a不会显示,但我不确定如何修改命令打印最后一个数组a。
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
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
>