2013-07-05 39 views
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 

回答

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

難道你詳細awk命令? –

+0

@Jérémie在答案中看到解釋 – Kent

+0

感謝您的解釋。現在我更瞭解它。我仍然有一個問題:當文件以兩行或更多行開始以'1'開頭時,命令不起作用。我知道這是因爲第二個條件在這種情況下不是真的,所以最後一個數組a不顯示,但我不知道如何修改命令來打印最後一個數組a。 –

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

有沒有可能您詳細介紹了perl命令? –