Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script - read two lines of file and read one line of another file

Tags:

shell

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.

like image 849
user3246010 Avatar asked Jun 01 '15 19:06

user3246010


1 Answers

If I'm interpreting your question correctly, you want to

  1. step through file1 start to finish, and
  2. insert the "next" line from file2 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.

like image 109
ghoti Avatar answered Nov 15 '22 08:11

ghoti