行から文字列を検索し、関連する行を追加します。

行から文字列を検索し、関連する行を追加します。

IDDSいくつかの(識別子)と(説明)行を含むファイルがあります。この値を持つ行とstring次の行を維持したいと思います。IDDSID

ID  number1 string
DS  item11
DS  item12
ID  number2 not_string
DS  item21 
DS  item22
ID  number3 string
DS  item31
DS  item32

次を返します。

ID  number1 string
DS  item11
DS  item12
ID  number3 string
DS  item31
DS  item32

答え1

not_string私が正しく理解したら、あなたの入力をテストするように変更します。

ID  number1 string                                                              
DS  item11                                                                      
DS  item12                                                                      
ID  number2 qwerty                                                               
DS  item21                                                                      
DS  item22                                                                      
ID  number3 string                                                              
DS  item31                                                                      
DS  item32

努力する:

$ awk '/ID/ && !/string/{flag=0;next};/string/{flag=1};flag' file 
ID  number1 string
DS  item11
DS  item12
ID  number3 string
DS  item31
DS  item32

答え2

sed -n '/ID.* s/p;//,/ID/{//!p;}' <<\DATA                              
    ID  number1 string
    DS  item11
    DS  item12
    ID  number2 not_string
    DS  item21
    DS  item22
    ID  number3 string
    DS  item31
    DS  item32
DATA

これだけ頼ってくださいPOSIXの定義正規表現アドレスの動作sed:

REが空の場合(つまり、モードが指定されていません) sed最後のコマンドで使用された最後のREが適用されたかのように動作する必要があります。(コマンド/address/または注文の一部としてs/ubsti/tute/任命される。

検索語の上部にある/ID.* s/住所が一致するとp印刷されます。ライン範囲は、最後のアドレスと次のアドレスに//,/ID/一致するラインの間に割り当てられます。IDワイヤー。{within;}この範囲に属するすべての行(最後の行で終わると不完全です)!not一致する項目//p印刷されます。

すべての発生は/ID.* s/私が明示的にp印刷した行であり、すべての発生は〜サイその行と次の/ID/行 - または(および含む)最後の行の最初に来る行です。

出力

ID  number1 string
DS  item11
DS  item12
ID  number3 string
DS  item31
DS  item32

関連情報