linux - 如何使用 shell 脚本找到离给定位置最近的网格点?

标签 linux shell unix awk

我有两个不同的文件。这些文件的一部分是:

文件 1:

ifile1.txt
21   10.3   70.32  09  
32   11.3   71.43  10
33   15.4   75.00  00
54   17.3   68.03  12
95   19.2   65.02  21
99   20.1   80.10  11
and so on......

Where 1st column is the ID, 
      2nd column refers to x-axis, 
      3rd column refers to y-axis,
      4th column refers to value

文件2:

ifile2.txt
10.10  70.12  10  
10.11  73.33  08
11.05  72.40  00
11.30  69.13  15
12.00  64.02  27
12.05  79.20  25
13.10  80.32  10  
13.11  75.43  06
14.05  74.00  02
14.20  69.03  15
16.40  65.02  13
16.55  68.10  14
and so on......

Where 1st column refers to x-axis, 
      2nd column refers to y-axis,
      3rd column refers to value

我想制作另一个文件,其输出将是(对于上面的例子):

ofile.txt
21   10.10  70.12  10  
32   11.05  71.40  10
33   14.05  74.00  02
54   16.55  68.10  14
95   16.55  68.10  14
99   16.55  68.10  14

Where 1st column is the ID (taken from ifile1.txt), 
      2nd and 3rd column refers to x-axis and y-axis (taken from ifile2.txt which are the nearest to those of ifile1.txt),
      4th column refers to corresponding value (taken from ifile2.txt)

我无法为此编写 shell 脚本。但是我的算法是:

for each $1 in ifile1.txt,
   for each $2 & $3 in ifile1.txt,
     find a $2 & $3 in ifile2.txt such that
       sqrt{[$2(ifile1.txt)-$2(ifile2.txt)]^2+[$3(ifile1.txt)-$3(ifile2.txt)]^2} is minimum for all $2 & $3 in ifile2.txt
     find correcsponding $4 from ifile2.txt
    write $1, $2, $3, $4 to ofile.txt

我非常感谢任何类型的建议或帮助。

最佳答案

这是 awk 中的一个简单解决方案。它在我的 Linux 上运行良好。 如果我的回答对您有用,请点击我回答左侧的灰色勾号。

#!/bin/bash
(($#!=2))&& { echo "Usage $0 1st_file 2nd_file"; exit 1; }
awk '
 BEGIN {p=fx=0; fn=""; maxd=1.1e11;}
 $0~"[^0-9. \t]" || NF!=4 && NF!=3 {next;}          # skip no data lines
 fn!=FILENAME {fx++; fn=FILENAME;}                  # fx: which file
 fx==1 { if(NF!=3){printf("Change the series of two input files\n"); exit 1;}
         x2[p]=$1; y2[p]=$2; d2[p++]=$3;next;}      # save the columns of first file
 fx==2 { mv=maxd; mp=0;                             # search minimal distance
           for(i=0; i<p; i++){
              dx=x2[i]-$2; dy=y2[i]-$3; dd=dx*dx+dy*dy;
              if(dd<mv){mv=dd; mp=i;}               # min value & min place
           }
           printf("%3d %6.2f %6.2f %3d\n", $1, x2[mp], y2[mp], d2[mp]);
         }
' $2 $1                                             # first is the 2nd_file!

关于linux - 如何使用 shell 脚本找到离给定位置最近的网格点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710230/

相关文章:

linux - tar: 无法将目录更改为 <dir>/<file>: 不是目录

linux - 如何打印目录中第一个和最后一个文件名的前四个字符

Linux命令——给文件名添加时间元素

unix - 如何在unix中从终端分离进程?

编译的C文件不可执行

python - linux磁盘缓冲区缓存是否使python cPickle比搁置更有效?

c++ - 将库放入 Linux 中的 exe 文件夹中

Linux Ubuntu Shell 脚本无限循环

bash - "set -euo pipefail"对 eval 有影响吗?

macos - TERM 环境变量未在 mac 上设置