如何从标记开始将文件的内容追加到另一个文件中?

时间:2011-04-05 23:21:10

标签: shell unix scripting sed replace

例如,file1包含:

Line 1
This is another line a
and another
<BEGIN>

few more lines.

file2包含:

/* This is a line With Special Characters */
/* Another line with @ special stuff \ ? # ! ~ */
/* and another */

我想在&lt;之后的点处将file2插入到file1中。开始&gt;声明。

我尝试了以下sed命令,但它似乎将'/'和'*'视为特殊字符。

TOINSERT=`cat file2`
sed "/BEGIN/ a $TOINSERT" file1 > output_file

但是,我收到一个错误,因为$ TOINSERT包含特殊字符。有没有办法逃脱$ TOINSERT的所有内容?

1 个答案:

答案 0 :(得分:3)

#!/bin/bash
sed '/<BEGIN>/ {
    r file2
    d
}' < file1 > output_file

注意: 如果您想与<BEGIN>保持一致,请使用:

 sed '/<BEGIN>/r file2' < file1 > output_file

概念证明

$ ./insertf.sh
Line 1
This is another line a
and another
/* This is a line With Special Characters */
/* Another line with @ special stuff \ ? # ! ~ */
/* and another */

few more lines.