Intersperse lines from two files Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Intersperse lines from two files without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a data file ($file1) which contains two lines of data per individual. I need to intersperse a third line of data from another data file ($file2). So my input looks like:

>cat $file1
  bob  1  1  0
  bob  1  0  1
  alan 0  0  1
  alan 0  1  1

>cat $file2
 bob  a  a  b
 alan a  c  a

So the desired result would be:

>cat $file3
  bob  1  1  0
  bob  1  0  1
  bob  a  a  b
  alan 0  0  1
  alan 0  1  1
  alan a  c  a

If I just needed to intersperse every other line I would have used paste like so:

>paste '-dn' $file1 $file2

What would be the best tool to use to achieve this? I am using zsh.

Answer

Just:

paste -d 'n' -- - - "$file2" < "$file1"

(provided $file2 is not -).

Or with GNU sed, provided $file2 (the variable content, the file name) doesn’t contain newline characters and doesn’t start with a space or tab character:

sed "2~2R$file2" "$file1" < "$file2"

With awk (provided $file1 doesn’t contain = characters (or at least that if it does, the part before it is not an acceptable awk variable name)):

export file2
awk '{print}
     NR % 2 == 0 {if ((getline l < ENVIRON["file2"]) > 0) print l}
    ' "$file1"
We are here to answer your question about Intersperse lines from two files - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji