マルチライン交換

マルチライン交換

私はこれを理解しようと長い時間を費やしました。偶然にも、これを行う必要はなく、別の方法を見つけました。しかし、私の精神状態のためにまだ答えを知りたいです。

sedマークアップをいくつかのテキストに置き換えるのはとても簡単です。私が理解していないのは、sed複数行、タブなどの複雑な書式を使用して巨大なテキストブロックを挿入する方法です。どうやってやったの?sed最高ですか、それとも何ですか?

答え1

ex実際にデータフローがない場合は、このような作業に使用します。exここに文書にコマンドを保存しました。

ex $FILENAME << END_EX_COMMANDS
" Find the mark, assuming it's an entire line
/^MARKER$/
" Delete the marker line
d
" Add the complex, multi-line text
a
Complex, vividly formatted text here.
Even more "specially" formatted text.
.
" The '.' terminates the a-command. Write out changed file.
w!
q
END_EX_COMMANDS

使用はexユーザーにとって利点です。ユーザーはすでにコマンドのキーストロークを知っていますが、盲目的に編集するように感じます。また、「:」モードで実行できるすべての操作だけでなく、複数の追加またはグローバル置換を実行することもできます。vivimvim

答え2

/tmp/insert.txt というファイルの表示にテキストを挿入するには、次の手順を実行します。

sed '/MARKER/ r /tmp/insert.txt' < inputfile

上記のsedコマンドは「inputfile」を読み、MARKERを探します。これが見つかったら、/tmp/insert.txtの内容を出力ストリームに挿入します。

タグ自体を削除するには:

sed '/MARKER/ {s/MARKER//; r /tmp/insert.txt
}' <inputfile

"}"閉じ括弧の前には改行文字が必要です。

最初のコマンドと同様に、sedはMARKERのある行で実行されます。 MARKER を空白に変更し、/tmp/insert.txt を読みます。

答え3

私はこのコマンドがあなたが探しているものだと思います:

r FILENAME
     As a GNU extension, this command accepts two addresses.

     Queue the contents of FILENAME to be read and inserted into the
     output stream at the end of the current cycle, or when the next
     input line is read.  Note that if FILENAME cannot be read, it is
     treated as if it were an empty file, without any error indication.

     As a GNU `sed' extension, the special value `/dev/stdin' is
     supported for the file name, which reads the contents of the
     standard input.

答え4

タグ自体を削除するには、次の行を試してください。

sed -e '/MARKER/ r /tmp/insert.txt' -e '/MARKER/d' < inputfile

または

sed -e '/MARKER/ {r /tmp/insert.txt' -e 'd }' < inputfile

関連情報