peterrobertlzlz
peterrobertlzlz

Reputation: 1

Insert text from a file to specific line numbers on another text file

How can I insert text from a file to specific line numbers in another text file? I was offered to use "sed", though with the flag "-i" there's no option to specify a text file, only "manually" loading text.

For example, how can achieve the following:

file1.txt:

55
66

file2.txt:

1
2
3
4
5

I wish to add file1 content to file2 content in a specific line number so at finish I will have:

file2.txt:

1
2
3
55
66
4
5

Can I acheive this using "sed"? or is there any other method?

Upvotes: 0

Views: 961

Answers (2)

Marek Nowaczyk
Marek Nowaczyk

Reputation: 257

And here it comes sed solution:

sed '3 r file1.txt' file2.txt

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207445

With awk maybe:

awk 'NR==4{system("cat file1.txt")} 1' file2.txt

That says... "Read file2.txt. If you have just read line 4, cat file1.txt. In general, print all lines - because 1 is true".

Or with vi maybe:

vi -c ':4:r file1.txt' -c ':wq!' file2.txt

That says... "Load file2.txt. When loaded, goto line 4, read in file1.txt. Save and quit".

Upvotes: 3

Related Questions