Unixでawkを使用して複数行パターン検索を実行するには?

Unixでawkを使用して複数行パターン検索を実行するには?

.sqlスクリプトを使用して、SQLスクリプトから複数行のパターンを検索する必要がありますawk

サンプルスクリプト -

select * from dept where department_name in ('abc'
, 'xyz', 'def') ;

department_name in上記の例では、閉じ括弧のパターンを検索する必要がありますが、その)パターンがスクリプトに複数回表示されることがあります。

上記の例では、「IN」句の値は複数の行にまたがっています。

ベストアンサー1

SQLが;ステートメント区切り文字として使用されているとします。

$ cat statements.sql
First bit;
Second thing;

More
of the same;

select * from dept where department_name in ('abc'
, 'xyz', 'def') ;

Getting to the end;

The
End;

その後、通常どおりに;レコード区切り文字を使用できます。awk

$ awk 'BEGIN { RS=";" } /department_name in ([^)]+)/ { print $0 ";" }' statements.sql


select * from dept where department_name in ('abc'
, 'xyz', 'def') ;

このパターンは/department_name in ([^)]+)/文字列department_name in (と1つ以上の非文字)(改行を含む)、)

このステートメントは、レコードが削除されたため、レコードの末尾に追加printされます(すべてのレコード区切り文字が削除されます)。;;awk

;ファイルの前の内容の後に空白行があるので、空白行が追加されます。以下を使用してフィルタリングできますsed -n '/[[:graph:]]/p'

$ awk 'BEGIN {RS=";"} /department_name in ([^)]+)/ { print $0 ";" }' statements.sql |
  sed -n '/[[:graph:]]/p'
select * from dept where department_name in ('abc'
, 'xyz', 'def') ;

おすすめ記事