Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 '-d\n' $file1 $file2

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

share|improve this question
up vote 9 down vote accepted

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"
share|improve this answer
    
much, thanks. i was wondering how paste could be usefully applied to a file w/out newlines... – mikeserv Jan 12 at 0:29

If you don't need to preserve the order of the people you could do cat $file1 $file2 | sort

share|improve this answer
    
This could work, but there might be use cases where I do need to preserve the order (but you can always assume the order of file1 and file2 are identical). – Simon O'Hanlon Jan 11 at 17:38

Other with awk

awk '
    FNR==NR{
        A[$1]=$0
        next
    }
    1
    !(NR%2){
        print A[$1]
    }
    ' file2 file1

Or if both files are proper sorted(as we use can paste) more simple:

awk '
    1
    !(NR%2){
        getline <"file1"
        print
    }
    ' file1
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.