【问题标题】:parsing an .kml file in bash script在 bash 脚本中解析 .kml 文件
【发布时间】:2013-08-30 15:10:38
【问题描述】:

我正在解析一个包含类似数据的 kml 文件:

<when>2013-08-15T15:00:39.744-07:00</when>
<gx:coord>13.7457943 52.0683374 0</gx:coord>
<when>2013-08-15T15:01:39.868-07:00</when>
<gx:coord>15.7458125 52.063955 0</gx:coord>

实际上我喜欢在 bash 中解析它,以便在一个循环中得到 whengx:coord

我已经走到这一步了:

cat test.kml | grep -e "gx:coord" | while read line 
do
   echo $line
done

这给了我所有的坐标,并且以同样的方式我会得到时间,读入一个数组我可能会达到我想要的,但必须有更好的方法:) 提前谢谢。

【问题讨论】:

  • 你能安装xmlstarlet(一个可以从bash访问的适当的XML解析/生成工具包)吗?通常,任何不涉及适当解析器的东西都是邪恶的黑客(另请参阅stackoverflow.com/a/1732454/14122)。
  • 解释 为什么 其他任何东西都会是 hack - 考虑一下您的条目没有用换行符分隔的情况; KML 格式当然不需要这些换行符。或者考虑当前称为gx 的命名空间具有不同前缀的情况。或者有一半的gx:coord 项目被注释掉,并且您希望能够排除它们的情况。等等。
  • 顺便说一下,要写一个如何正确执行此操作的示例,我需要知道文件前面的xmlns:gx 属性是如何设置的;这里给出的子字符串是不够的。

标签: linux bash shell scripting terminal


【解决方案1】:

如果你的行是有序的,则使用 bash:

while read WHEN && read GXCOORD; do
    echo "$WHEN : $GXCOORD"
done < test.kml

或者可以这样做:

while read WHEN && read GXCOORD; do
    echo "$WHEN : $GXCOORD"
done < <(exec grep -Fe "<when>" -e "<gx:coord>" test.kml)

也许还可以去掉标签:

while read WHEN && read GXCOORD; do
    WHEN=${WHEN##*'<when>'} WHEN=${WHEN%%'</when>'*}
    GXCOORD=${GXCOORD##*'<gx:coord>'} GXCOORD=${GXCOORD%%'</gx:coord>'*}
    echo "$WHEN : $GXCOORD"
done < <(exec grep -Fe "<when>" -e "<gx:coord>" test.kml)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-09
    • 2013-07-24
    • 2016-02-08
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 2014-04-28
    • 2010-12-06
    相关资源
    最近更新 更多