Say, I have two files.
File1 contains:
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
and File2 contains:
anotherline1
anotherline2
anotherline3
I want to do a while loop so that it outputs this into a File3:
line1
line2
anotherline1
line3
line4
anotherline2
line5
line6
anotherline3
line7
line8
anotherline1
line9
line10
anotherline2
I've searched here for an answer but I can't figure out how to do it. I must say I'm pretty noob at shell scripting...
Also: The "while loop" should be until reaching end of file1. Doesn't matter how long is File2, actually, in my personal scenario, File2 will always be shorter than File1. Output should be: File1Line1, File1Line2, File2Line1, File1Line3, File1Line4, File2Line2.... etc
Any help?
note: if this was already answered before, then mods please close this question. I just couldn't find any answers after googling for some hours.
EDIT: Added clarification of when to end the loop.
If I'm interpreting your question correctly, you want to
file1
start to finish, andfile2
after every two lines, rotating back to the top of file2
whenever you run out of content.If that's the goal, you could do it with awk in a number of ways, but the following shell snippet would probably do.
#!/usr/bin/env bash
mapfile -t file2 < file2
max=${#file2[@]}
while read line; do
((count++))
echo "$line"
if [[ $((count%2)) == 0 ]]; then
if [[ next -ge max ]]; then
next=0
fi
echo "${file2[next++]}"
fi
done < file1
This has the down side of loading all of file2
into memory as an array. If that's a problem because the file is too big, you can perhaps add some shell glop to go find specific lines at each invocation of the loop, though that will be very slow. Better yet, define your problem more specifically, or consider alternate tools! :-)
Note also that the mapfile
command is a bash-4-ism, so if you're on an older Linux, or OSX (which still ships with bash 3), you'll need a different solution ... or an upgrade to bash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With