Question: I have text files as shown below.

```
 CA     21.660  -6.795  11.323 
  C     28.811  -9.801  16.262
  O     23.221  -9.266  13.799
  CB    33.528 -11.934  17.900
  N     21.660  -6.795  11.323
  O     32.410  -8.539  16.566

```

I want to calculate the distances between the coordinates of atoms. For example, I would like to read all files in a folder and calculate the distances between first and second atom,first and third, first and fourth, etc.Then, second and third, second and fourth, second and fifth etc.The formula is SQRT ((X1-X2)^2 + (Y1-Y2)^2 + (Z1-Z2)^2). I would like to save the outputs from each file to another folder with the names of input files. How can I do this with awk?

desired output

```
CA-C  4.52
CA-O  3.80
CA-CB 5.68
CA-N  8.94
--
--
--
N-O   5.98 

```

your help would be appreciated!!

Answer: 
Below is the code in awk:

```
awk '{a[NR]=$0}
     END
     { 
       for(i=1;i<=NR;i++)
        {split(a[i],k);
         for(j=i+1;j<=NR;j++)
          {
           split(a[j],l);
           dist=(k[2]-l[2])*(k[2]-l[2])+(k[3]-l[3])*(k[3]-l[3])+(k[4]-l[4])*(k[4]-l[4]);
           print k[1]"-"l[1],sqrt(dist);
          }
        }
     }' your_file

```

And Below is the Test:

```
> cat temp
 CA     21.660  -6.795  11.323 
  C     28.811  -9.801  16.262
  O     23.221  -9.266  13.799
  CB    33.528 -11.934  17.900
  N     21.660  -6.795  11.323
  O     32.410  -8.539  16.566

```

Execution:

```
> awk '{a[NR]=$0}END{for(i=1;i<=NR;i++){split(a[i],k);for(j=i+1;j<=NR;j++){split(a[j],l);dist=(k[2]-l[2])*(k[2]-l[2])+(k[3]-l[3])*(k[3]-l[3])+(k[4]-l[4])*(k[4]-l[4]);print k[1]"-"l[1],sqrt(dist);}}}' temp
CA-C 9.19601
CA-O 3.83055
CA-CB 14.5092
CA-N 0
CA-O 12.0869
C-O 6.13194
C-CB 5.42981
C-N 9.19601
C-O 3.82595
O-CB 11.4092
O-N 3.83055
O-O 9.62406
CB-N 14.5092
CB-O 3.81517
N-O 12.0869
> 

```
A Perl solution could be:

```
#!/usr/bin/perl
use strict;
use warnings;

my @data = map [split], <DATA>;

for (my $i = 0; $i < @data; $i++) {
    for (my $j = $i+1; $j < @data; $j++) {
        my $d = distance( @data[$i, $j]);
        printf("%-6s%7.4f\n",
            join("-", map $_->[0], @data[$i, $j]), $d) if $d <= 6;
    }
}

sub distance {
    my ($coord1, $coord2) = @_;
    my $sum;
    for my $k (1 .. $#$coord1) {
        $sum += ($coord1->[$k] - $coord2->[$k])**2;
    }
    return sqrt $sum;
}

__DATA__
CA     21.660  -6.795  11.323 
C     28.811  -9.801  16.262
O     23.221  -9.266  13.799
CB    33.528 -11.934  17.900
N     21.660  -6.795  11.323
O     32.410  -8.539  16.566

```