パターンマッチングの間にファイルAの内容をファイルBに追加する方法

パターンマッチングの間にファイルAの内容をファイルBに追加する方法

2つのファイルがあります。

Aファイルの内容は次のとおりです。

etc...
this is a test file having \@ and \# and \$ as well
looking for awk or sed solution to print this content in another file between the matching pattern
etc....

Bファイルの内容は次のとおりです。

file-B begin 
this is a large file containing many patterns like 
pattern-1 
pattern-2 
pattern-2 
pattern-3 
pattern-2 
pattern-4 
file-B end 

ファイルBの出力は次のようになります。

file-B begin 
this is a large file containing many patterns like 
pattern-1 
pattern-2 
pattern-2 
etc... 
this is a test file having \@ and \# and \$ as well 
looking for awk or sed solution to print this content in another file between the matching pattern 
etc.... 
pattern-3 
pattern-2 
pattern-4 
file-B end 

ファイルBのモード2とモード3の間でファイルAの内容を印刷したい。

現在私はこれを使用しています:

awk '/pattern-2/{c++;if(c==2){printf $0; print "\n"; while(getline line<"file-A"){print line};next}}1' file-B

それはうまくいきますが、これら2つのパターンを検索してからそれらの間に別のファイルコンテンツを入れるものが必要です。

ベストアンサー1

awk -v file="file-A" '
  last=="pattern-2" && $0=="pattern-3"{
    while ((getline line < file)>0) print line
    close(file)
  }
  {last=$0}1
' file-B

または、文字列の代わりに正規表現パターンを使用している場合は、次のようなものを使用してください。

  last ~ /pattern-2/ && /pattern-3/{

2行目。

おすすめ記事