3

I have two text files, whose content is as follows;

data_1:473428800.0 0 0.000004 1.00 WETZTROPMCIL   #4 columns, several lines
       473429100.0 0 0.000002 1.00 WETZTROPMCIL

data_2:473428800.0 0 2.100000 1.00 DRYTROPMCIL    #4 columns, several lines
       473429100.0 0 2.200000 1.00 DRYTROPMCIL

I need to add each line of the 3rd column of one file to the respective line of the 3rd column in the other file, and substitute these sums to the 3rd column of data_1, in a new file, as below;

merged_data= data_1:473428800.0 0 2.1000004 1.00 WETZTROPMCIL   #4 columns, several lines
                    473429100.0 0 2.2000002 1.00 WETZTROPMCIL

2 Answers 2

5

Try:

paste data_1 data_2 | awk '{$3=sprintf("%.10g", $3+$8); NF=5; print}'

Notes:

  • I see 5 fields per file not 4 as stated in OP.

  • paste will merge lines from the two files.

  • awk will see lines with 10 fields each. NF=5 tells it to keep only the first 5, which are from data_1.

  • The float is printed with [s]printf's format %.10f. This might or might not be ok. See man 3 printf.

  • If sorting is needed, it could be done with process substitution:

    paste <(sort [args] data_1) <(sort [args] data_2) | awk ...
    
2

Matei's method should guarantee the lines are in the same order. Therefore, the following way will be more secure.

sort -k 1n data_1 > data_1_sort
sort -k 1n data_2 > data_2_sort
paste data_1_sort data_2_sort| awk '{$3=sprintf("%.10g", $3+$8); NF=5; print}'

You must log in to answer this question.

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