say i have file1 with content
line1
line2
line3
and another file2 with content
lineA
lineB
lineC
lineD
lineE
lineF
lineG
lineH
lineI
I want to make file2 as
lineA
lineB
lineC
line1
lineD
lineE
lineF
line2
lineG
lineH
lineI
line3
say i have file1 with content
line1
line2
line3
and another file2 with content
lineA
lineB
lineC
lineD
lineE
lineF
lineG
lineH
lineI
I want to make file2 as
lineA
lineB
lineC
line1
lineD
lineE
lineF
line2
lineG
lineH
lineI
line3
Here is a way to do it with paste
cat file2 | paste -d'\n' - - - file1
The dash argument for paste
means to read from the standard input, which is the cat file2
output, while the fourth argument is file1
. So, with three dashes, we will paste every 3 lines of one file with 1 from another and the delimiter is the newline character (-d'\n'
).
This will work in case of remaining lines in any of these files, as paste will continue when EOF
is found for one of the inputs. But it may print a couple of empty lines in that case, so you can pipe to any command to remove them, (supposing you don't have actual empty lines in your files), for example
cat file2 | paste -d'\n' - - - file1 | sed '/^$/d'
This python code will do it, the parameters in your case would be
python interlace.py file1 file2 file3 3
I would suggest just using a mv file3 file2
afterward if you want it to be in-place. This is because if you start writing to file2 before you've read everything it can be overwritten
import sys
if len(sys.argv[1:]) == 4:
file1 = open(sys.argv[1], 'r')
file2 = open(sys.argv[2], 'r')
file3 = open(sys.argv[3], 'w')
line_count = int(sys.argv[4])
current_counter = 0
for file2_line in file2.readlines():
current_counter += 1
file3.write(file2_line)
if current_counter == line_count:
file3.write(file1.readline())
current_counter = 0
for file1_line in file1.readlines():
file3.write(file1_line)
file3.close()
This also works in the cases where file1 runs out of lines early, in which case file2's lines continue as normal, and when file1 has extra lines they just get added to the end.
This might work for you (GNU sed):
n=3
sed "$n~$n"'R file1' file2
After the third line and subsequently every third line of file2, append a line from file1.
Using awk and getline
:
awk '1;NR%3==0{if((getline < "file1")>0)print}' file2
lineA
lineB
lineC
line1
lineD
...
You could probably obfuscate it to awk '1;NR%3==0&&(getline < "file1")' file2
(untested).