8

2 つのパターンの間にいくつかの大きなコードを追加したい:

File1.txt

This is text to be inserted into the File.

infile.txt

Some Text here
First
Second
Some Text here

FirstSecondの間にFile1.txtコンテンツを追加したい:

望ましい出力:

Some Text here
First
This is text to be inserted into the File.
Second
Some Text here

sed コマンドで 2 つのパターンを使用して検索できますが、それらの間にコンテンツを追加する方法がわかりません。

sed '/First/,/Second/!d' infile 
4

4 に答える 4

10

ファイルの読み取りを/r表すため、次を使用します。

sed '/First/r file1.txt' infile.txt

ここでいくつかの情報を見つけることができます: 「r」コマンドを使用してファイルを読み取る

インプレース エディションの場合-iは (つまり、 ) を追加します。sed -i '/First/r file1.txt' infile.txt

文字の大文字と小文字に関係なくこのアクションを実行するには、いくつかのパターンの前にテキストを追加するときに大文字と小文字を区別しないで sed を使用するIで提案されているようにマークを使用します。

sed 's/first/last/Ig' file

コメントで示されているように、上記の解決策は、2 番目のパターンを考慮せずに、パターンの後に特定の文字列を出力するだけです。

そのためには、フラグを付けて awk を実行します。

awk -v data="$(<patt_file)" '/First/ {f=1} /Second/ && f {print data; f=0}1' file

これらのファイルが与えられた場合:

$ cat patt_file
This is text to be inserted
$ cat file
Some Text here
First
First
Second
Some Text here
First
Bar

コマンドを実行しましょう:

$ awk -v data="$(<patt_file)" '/First/ {f=1} /Second/ && f {print data; f=0}1' file
Some Text here
First                             # <--- no line appended here
First
This is text to be inserted       # <--- line appended here
Second
Some Text here
First                             # <--- no line appended here
Bar
于 2013-05-30T12:40:24.603 に答える
1

awkフレーバー:

awk '/First/ { print $0; getline < "File1.txt" }1' File2.txt
于 2013-05-30T12:52:26.373 に答える