将命令的结果存储在变量中

时间:2013-10-04 09:16:08

标签: bash proj

我正在尝试将命令的结果存储在变量中,但无法找出正确的语法。此命令可以完美地运行:

echo "-868208.53 -1095793.57 512.30" | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326

这就是我尝试使用此示例并将其应用于我的数据的方式,但outcord分配错误:

#!/usr/bin/bash
filename="$1"
while read -r line
do
    name=$line
    a=( $name )
    coord= ${a[1]} ${a[2]}
    outcoord= $("echo $coord | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326")
    echo $outcoord
done < "$filename"

我得到的示例错误:

remap.sh: line 7: -515561.05: command not found
remap.sh: line 8: echo  | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326: command not found
remap.sh: line 7: -515542.01: command not found
remap.sh: line 8: echo  | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326: command not found

示例数据:

1 -515561.05 -1166540.03
2 -515542.01 -1166548.76
3 -515519.61 -1166552.19
4 -515505.29 -1166550.25
5 -515477.05 -1166546.82
6 -515431.12 -1166534.06
7 -515411.45 -1166517.39

如何将命令结果分配给变量outcoord

2 个答案:

答案 0 :(得分:2)

你有很多问题。以下第一行:

coord= ${a[1]} ${a[2]}
  • 切勿在{{1​​}}周围添加空格。
  • 引用变量,如果它们包含空格。

替换以下行:

=

name=$line
a=( $name )
coord= ${a[1]} ${a[2]}
outcoord= $("echo $coord | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326")
echo $outcoord

它应该是好的。

如果你只想要数组的最后两个元素,你可以说:

outcoord=$(echo "${line[@]}" | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326)
echo "$outcoord"

而不是:

outcoord=$(echo "${line[1]} ${line[2]}" | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326)

while read -r line

将读取的行分配给数组while read -a line

答案 1 :(得分:0)

尝试删除双引号;即:

    outcoord=$(echo $coord | cs2cs +init=esri:102067 +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +to +init=epsg:4326)

否则bash会将整个字符串解释为命令的名称。