パターンに一致する各連続行シーケンスの最初の行のみを保持します。

パターンに一致する各連続行シーケンスの最初の行のみを保持します。

2つ以上の連続する行に特定のパターンが含まれている場合は、一致する行をすべて削除し、最初の行のみを保持します。

次の例では、2つ以上の連続する行に「論理IO」が含まれている場合は、一致するすべての行を削除し、最初の行は維持する必要があります。

入力ファイル:

select * from test1 where 1=1
testing logical IO 24
select * from test2 where condition=4
parsing logical IO 45
testing logical IO 500
handling logical IO 49
select * from test5 where 1=1
testing logical IO 24
select * from test5 where condition=78
parsing logical IO 346
testing logical IO 12

結果ファイル:

select * from test1 where 1=1
testing logical IO 24
select * from test2 where condition=4
parsing logical IO 45
select * from test5 where 1=1
testing logical IO 24
select * from test5 where condition=78
parsing logical IO 346

ベストアンサー1

使用awk:

awk '/logical IO/ {if (!seen) {print; seen=1}; next}; {print; seen=0}' file.txt 
  • /logical IO/ {if (!seen) {print; seen=1}; next}行が含まれていることを確認し、logical IO変数がseenfalseの場合、つまり前の行が含まれていない場合は、行をlogical IO印刷して設定し、seen=1次の行に移動します。それ以外の場合は、前の行がすでに含まれているので、次の行に移動します。logical IO

  • 他の行の場合は、{print; seen=0}行とセットを印刷します。seen=0

例:

$ cat file.txt 
select * from test1 where 1=1
testing logical IO 24
select * from test2 where condition=4
parsing logical IO 45
testing logical IO 500
select * from test5 where 1=1
testing logical IO 24
select * from test5 where condition=78
parsing logical IO 346
parsing logical IO 346
testing logical IO 12

$ awk '/logical IO/ {if (!seen) {print; seen=1}; next}; {print; seen=0}' file.txt 
select * from test1 where 1=1
testing logical IO 24
select * from test2 where condition=4
parsing logical IO 45
select * from test5 where 1=1
testing logical IO 24
select * from test5 where condition=78
parsing logical IO 346

おすすめ記事