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

标签 shell unix scripting sed replace

例如,file1 包含:

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

few more lines.

文件2包含:

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

我想将 file2 插入到 file1 中 语句之后的位置。

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

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

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

最佳答案

#!/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.

关于shell - 如何从标记开始将一个文件的内容追加到另一个文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5559717/

相关文章:

string - 将大字符串拆分为子字符串

shell - sudo 作为另一个用户,密码来自 stdin

bash - 将文件的每一行作为参数传递给命令?

linux - 调用未安装的例程时 Shell 脚本不会失败

java - 同时从多个线程调用 shell 脚本

linux - shell 脚本 :How to pass script's command-line arguments through to commands that it invokes?

坐标传递给 XDrawImageString()

linux - 有没有办法从文件底部读取直到找到某个字符

Bash 脚本 "Usage"输出格式

python - 如何在 Django View 中运行命令行 python 脚本?