Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux -- How to cut a column from one file and paste into another in a one-line command?

Tags:

linux

cut

paste

I would like to use the linux cut command to extract a column from a file, then use the paste command to insert the same column into a second file. I can do this by saving the results of the cut command, and then running paste on it and the second file. But it seems to me there must be some one-liner for doing this that doesn't involve saving intermediate results. Anyone know what that is? Thanks.

For example, the first file might look like

date        weight
1-1-2010    weight1
1-2-2010    weight2
1-3-2010    weight3

and the second might look like

date        blood_press
1-1-2010    bp1
1-2-2010    bp2
1-3-2010    bp3

and I would like output like

date       weight     blood_press
1-1-2010   weight1    bp1
1-2-2010   weight2    bp2
1-3-2010   weight3    bp3

Needless to say, the data is alot larger and more complicated than this. But this gives the idea of what I need to do. Thanks again.

P.S. For reasons too detailed to go into, the "join" command isn't going to work.

like image 409
bob.sacamento Avatar asked Feb 15 '23 19:02

bob.sacamento


1 Answers

If you can live with a tab separator (or another single character) you can do

cut [column-spec] file1 | paste file2 - > file3

The - in the paste command reads stdin, which of course contains the lines produced by cut. There's no matching on values, this is a straight line-for-line copy and paste.

like image 177
Jim Garrison Avatar answered Feb 27 '23 11:02

Jim Garrison