How to add a column from a file to another file

前端 未结 3 1647
梦谈多话
梦谈多话 2020-12-25 11:31

I have a file with two columns as

1 1
2 3
3 4

and a file with one column as

6
7
9

I would like to add the

相关标签:
3条回答
  • 2020-12-25 12:21
    $ pr -mts' ' file1 file2
    1 1 6
    2 3 7
    3 4 9
    
    $ paste -d' ' file1 file2
    1 1 6
    2 3 7
    3 4 9
    
    0 讨论(0)
  • 2020-12-25 12:26

    A pure bash solution can be:

    exec 3<twofile
    while read x; do read -u 3 y; echo $x $y; done <onefile
    

    Infiles:

    cat >onefile <<XXX
    1 1
    2 3
    3 4
    XXX
    cat >twofile <<XXX
    6
    7
    9
    XXX
    

    Output:

    1 1 6
    2 3 7
    3 4 9
    
    0 讨论(0)
  • 2020-12-25 12:32
    awk 'NR==FNR{a[NR]=$0;next}{print a[FNR],$0}' file1 file2
    

    Note: Will work with files of same length. If file lengths' are different, go with sudo_O's solution.


    Just for the heck of it, here is an awk command that I think should simulate paste. Purely for fun though, if I were you I would still go with sudo_O's solution (or may be not!)

    awk 'NR==FNR{a[++y]=$0;next}{b[++x]=$0}
    END{z=x>y?x:y;while(++i<=z){print a[i],b[i]}}' file1 file2
    
    0 讨论(0)
提交回复
热议问题