0

I know how to replace a line with another line or several other lines with tools like sed. But is there an easy way, to replace a line in a file with the whole content of a second file?

So, let's have an example. I have a file called file1.txt:

A 1
B 2
C 3

And I have a second file file2.txt:

line 1
line 2
line 3

Now, I want to replace line 2 with the whole content of file1.txt, so in the end, it should look like this

line 1
A 1
B 2
C 3
line 3

One way I could think about would be something like this:

sed -i "s/line 2/$(cat file1.txt)/g" file2.txt. 

But then I also have to check some special characters like / and maybe more. I have to assume, that every possible readable character could be in file1.txt.

So, back to my question: Is there an easy way, to replace a line in a file with the whole content of a second file? It doesn't have to be sed. It could be also another tool, if it could do the job better...

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
devopsfun
  • 1,407

2 Answers2

3
sed -e '/^line 2$/{r file1.txt' -e 'd;}' file2.txt

The sed script is

/^line 2$/{
    r file1.txt
    d
}

The newline after the filename file1.txt is mandatory, so splitting it up into separate -e expressions on the command line makes it arguably more readable than

sed '/^line 2$/{r file1.txt
d;}' file2.txt

The script looks for a line whose content is line 2. When this is found, the contents of file1.txt is immediately outputted and the original line deleted.

Using sed -i will make the changes in-line in file2.txt (not recommended).

Kusalananda
  • 333,661
0

Using vi

Goto the line, then :

!!cat filename

Current line replaced with contents of file.

X Tian
  • 10,463