sedを使用してパターン付きの行を次の行にリンクするには?

sedを使用してパターン付きの行を次の行にリンクするには?

フォーラムでそのケースが見つからなかったので質問しました。

入力ファイルは次のとおりです。

module  
x(a,b,c)  
module  
y(d,e,f,  
g,h,i)  
module  
z(j,k,l)

出力ファイルは次のようにする必要があります。

module x(a,b,c)  
module y(d,e,f,  
g,h,i)  
module z(j,k,l)

ベストアンサー1

あなたが望むのは、moduleこの行を次の行に関連付けることです。

使用sed:

$ sed '/^module/N;s/\n//' file
module  x(a,b,c)
module  y(d,e,f,
g,h,i)
module  z(j,k,l)

データをそのままコピーして貼り付ける場合であり、各行の末尾に空白を置きます。

このsedコマンドは、読み取ったように各行を印刷しますが、文字列で始まる行に遭遇すると、module次の行の間に挿入された改行文字を追加します(これを行いますN)。結果を印刷する前に交換して改行を削除します。

データに末尾のスペースがない場合は、次のようにします。

$ sed '/^module/N;s/\n/ /' file
module x(a,b,c)
module y(d,e,f,
g,h,i)
module z(j,k,l)

必要な場合に備えて(入力行の末尾にスペースがないと仮定):

$ sed -e '/^module/bpp' -e 'H;$bpp' -e 'd' \
      -e ':pp' -e 'x;/^$/d;s/\n/ /g' file
module x(a,b,c)
module y(d,e,f, g,h,i)
module z(j,k,l)

注釈付きsedスクリプト:

/^module/ b print_previous; # print previous record
H;                          # append this line to hold space
$         b print_previous; # print previous (last) record
d;                          # end processing this line

:print_previous;            # prints a record accumulated in the hold space
x;                          # swap in the hold space
/^$/ d;                     # if line is empty, delete it
s/\n/ /g;                   # replace embedded newlines by spaces
                            # (implicit print)

報酬ed内容:

$ printf '%s\n' 'g/^module/ j' ,p Q | ed -s file
module  x(a,b,c)
module  y(d,e,f,
g,h,i)
module  z(j,k,l)

上記のコードは、文字列で始まるすべての行を次の行にmodule関連付けます。

$ printf '%s\n' 'v/^module/ -,.j' ,p Q | ed -s file
module  x(a,b,c)
module  y(d,e,f,  g,h,i)
module  z(j,k,l)

上記の行をリンクしてください。いいえmodule文字列で始まるより早いワイヤー。

おすすめ記事