簡単な仕事ed:
ed -s file1 <<IN
/Pointer/-r file2
,p
q
IN
-r file1アドレス指定された行の後に指定されたファイルを読み込みます。この場合、これはに一致する最初の行の前の行Pointerです。そのため、複数行で発生したfile2場合でも1回だけコンテンツが挿入さPointerれます。一致する各行の前に挿入する場合は、globalフラグを追加します。
ed -s file1 <<IN
g/Pointer/-r file2
,p
q
IN
交換する,pとwあなたはその場でファイルを編集する場合。
sedほとんどの場合、受け入れられた答えは機能しますが、マーカーが最後の行にある場合、コマンドは期待どおりに機能しませんFile1。マーカーの後にコンテンツを挿入します。
私は最初に試しました:
sed '/Pointer/{r file1
N}' file2
これも正常に動作します(rサイクルの終わりに魔法を行うように)が、マーカーが最後の行にある場合は同じ問題があります(N最後の行の後にext行はありません)。これを回避するには、入力に改行を追加します。
sed '/Pointer/{              # like the first one, but this time even if the
r file1                      # marker is on the last line in File2 it
N                            # will be on the second to last line in
}                            # the combined input so N will always work;
${                           # on the last line of input: if the line is
/^$/!{                       # not empty, it means the marker was on the last
s/\n$//                      # line in File2 so the final empty line in the
}                            # input was pulled i\n: remove the latter;
//d                          # if the line is empty, delete it
}' file2 <(printf %s\\n)
これによりfile2、一致する各行の前にコンテンツが挿入されます。最初に一致する行の前にのみ挿入するには、loopを使用して、nファイルの終わりに達するまでext行をプルするだけです。
sed '/Pointer/{
r file2
N
:l
$!n
$!bl
}
${
/^$/!{
s/\n$//
}
//d
}' file1 <(printf %s\\n)
これらのsedソリューションを使用すると、その場で編集する機能が失われます(ただし、別のファイルにリダイレクトできます)。