3

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.

| improve this question | | | | |
9

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

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

| 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 '16 at 17:38
2

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
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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