3

I have a bunch of files (file1, file2,file3, ...) with two columns. For example, file1 looks like:

0.12 0
0.32 0
0.42 1
0.23 0

and file2 looks like:

0.34 1
0.55 1
0.31 1
0.99 0

I wonder how to properly merge these files to one file with only first columns. The output file should be like:

0.12 0.34
0.32 0.55
0.42 0.31
0.23 0.99

My initial (unsuccessful) attempt is here:

pr -t -s ',' -m <(< file1 | cut -d ' ' -f 1) <(< file2 | cut -d ' ' -f 1)
4
  • steve's answer demonstrates that your problem statement is unclear.  Please describe more clearly what you mean by "merge" and show two or more sample files (it's probably sufficient to show only two or three lines from each) and then show the desired output.  BTW, are you guaranteeing that all the files are the same length (if that's appropriate)? Commented Jul 23, 2015 at 6:32
  • 1
    BTW, < filename | command isn't going to work.  Try < filename  command (leaving out the |) or command < filename (putting the I/O redirection at the end of the command). Commented Jul 23, 2015 at 6:37
  • Thanks, that helps a lot. The following line works : pr -t -s' ' -m <(< file1 cut -d ' ' -f 1) <(< file2 cut -d ' ' -f 1 )
    – Andrej
    Commented Jul 23, 2015 at 6:43
  • 1
    (The five-minute editing window ran out.)  By the way, < filename | command isn't going to work.  Try < filename  command (omitting the |) or command < filename (putting the I/O redirection at the end of the command).  In fact, most commands (including cut) will read from file(s) whose name(s) are passed as arguments, so you can say simply command filename. Commented Jul 23, 2015 at 6:43

2 Answers 2

2

Since the number of files is large, awk sounds like a good choice:

awk '
    {line[FNR] = line[FNR] $1 OFS}
    END {for (i=1; i<=FNR; i++) print line[i]}
' file1 file2 file3 ...
0

Simple approach:

$ cat file1
0.12 0
0.32 0
0.42 1
0.23 0
$ cat file2
0.92 0
0.92 0
0.92 1
0.93 0
$ cat file1 file2 | cut -f1 -d" "
0.12
0.32
0.42
0.23
0.92
0.92
0.92
0.93
$
1
  • I need to add new files by columns.
    – Andrej
    Commented Jul 23, 2015 at 6:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .