Is there a linux command to copy a file into another file at a specific point?

172 Views Asked by At

In linux can you copy one file into another file at a specific line(using a terminal command)?

Ex.
File 1:

this is 
file 1

File 2:

this is
file 2

New File:

this is
this is
file 2
file 1
3

There are 3 best solutions below

0
Gryphius On

you could use paste

$ cat file1 
this is
file 1
$ cat file2
this is
file 2
$ paste -d '\n' file2 file1 > new_file
$ cat new_file 
this is
this is
file 2
file 1
0
Phil Perry On

I don't think there's any native command to do this, but you could do it at least a couple of ways.

1a. file chunk1 = head _n_ lines of file 1
1b. file chunk2 = tail _m_ lines of file 1
1c. cat chunk1 file_2 chunk2 > new_file

or write a simple script (e.g., in Perl) to

2a. read _n_ lines of file 1 and write them out to new_file
2b. read file 2 and write it out to new_file
2c. finish reading remaining lines of file 1 and write them out to new_file
0
Robb On
  1. Use "head --lines=$NLINES input1 >output" to output the first $NLINES
  2. Use "cat input2 >>output" to insert the second file
  3. Use "tail --lines=+$[NLINES+1] input1 >>output" to output the remaining lines