Shell script to calculate nearest coordinates

Shell script to calculate nearest coordinates

The format of the coordinate data file geo.log is as follows:

beijing(116.405285,39.904989)
tinajin(117.190182,39.125596)
hebei(114.502461,38.045474)
shanxi(112.549248,37.857014)
neimenggu(111.670801,40.818311)
liaoning(123.429096,41.796767)
jilin(125.3245,43.886841)
heilongjiang(126.642464,45.756967)
shanghai1(121.472644,31.231706)
jiangsu(118.767413,32.041544)
zhejiang(120.153576,30.287459)
anhui(117.283042,31.86119)
fujian(119.306239,26.075302)
jiangxi(115.892151,28.676493)
shandong(117.000923,36.675807)
henan(113.665412,34.757975)
hubei(114.298572,30.584355)
hunan(112.982279,28.19409)
guangdong(113.280637,23.125178)
guangxi(108.320004,22.82402)
hainan(110.33119,20.031971)
chongqing(106.504962,29.533155)
sichuan(104.065735,30.659462)
guizhou(106.713478,26.578343)
yunnan(102.712251,25.040609)
xizang(91.132212,29.660361)
shanxi3(108.948024,34.263161)
gansu(103.823557,36.058039)
qinghai(101.778916,36.623178)
ningxia(106.278179,38.46637)
xinjiang(87.617733,43.792818)
taiwan(121.509062,25.044332)
xianggang(114.173355,22.320048)
aomen(113.54909,22.198951)

Write script filecoordinate.sh

#!/bin/bash

# 计算两点之间的距离
function distance {
    
    
    x1=$1
    y1=$2
    x2=$3
    y2=$4
    echo "scale=2; sqrt(($x2 - $x1)^2 + ($y2 - $y1)^2)" | bc
}

# 检查参数是否传入
if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Usage: $0 <coordinates file> <point name>"
    exit 1
fi

# 从文件中读取坐标点并计算最近的点
while IFS='(' read -r name rest; do
    name=$(echo $name | tr -d ' ')  # 去除空格
    rest=$(echo $rest | tr -d ')')  # 去除右括号
    IFS=',' read -r x y <<< "$rest"
    if [ "$name" = "$2" ]; then
        xA=$x
        yA=$y
    else
        dist=$(distance $xA $yA $x $y)
        if [ -z "$minDistance" ] || (( $(echo "$dist < $minDistance" | bc -l) )); then
            minDistance=$dist
            closestPoint=$name
        fi
    fi
done < "$1"  # 从传入的文件中读取坐标点

echo "距离 $2 最近的点是 $closestPoint,距离为 $minDistance"

Execute script filecoordinate.sh

Shell script to calculate nearest coordinates

Guess you like

Origin blog.csdn.net/qq_24330181/article/details/134750747