在 bash 中将一个文件附加到另一个文件的中间

Wya*_*tte 7 linux bash merge file append

我需要将一个文件附加到另一个文件的特定位置。我得到了行号,所以我的文件是:

file1.txt:

I
am
Cookie
Run Code Online (Sandbox Code Playgroud)

虽然第二个是

file2.txt:

a
black
dog
named
Run Code Online (Sandbox Code Playgroud)

所以,解决之后,file1.txt应该是这样的

I
am
a
black
dog
named
Cookie
Run Code Online (Sandbox Code Playgroud)

The solution should be compatible with the presence of characters like " and / in both files.

Any tool is ok as long as it's native (I mean, no new software installation).

Ard*_*dit 9

除了 RavinderSingh13 建议使用的另一个选项:在特定行之后添加intosed的文本:file2.txtfile1.txt

sed -i '2 r file2.txt' file1.txt
Run Code Online (Sandbox Code Playgroud)

输出:

I
am
a
black
dog
named
Cookie
Run Code Online (Sandbox Code Playgroud)

进一步在匹配的模式后添加文件:

sed -i '/^YourPattern/ r file2.txt' file1.txt
Run Code Online (Sandbox Code Playgroud)


Rav*_*h13 3

您可以尝试关注并告诉我这是否对您有帮助。

awk 'FNR==3{system("cat file2.txt")} 1' file1.txt
Run Code Online (Sandbox Code Playgroud)

输出如下。

I
am
a
black
dog
named
Cookie
Run Code Online (Sandbox Code Playgroud)

说明:在读取名为 file1.txt 的 Input_file 时检查行号是否为 3,如果是,则使用 awk 的系统实用程序来帮助我们调用 shell 的命令,然后我使用 cat 命令打印 file2.txt。然后提及 1 将打印 file1.txt 中的所有行。因此,我们可以将 file2.txt 中的行连接到 file1.txt 中。