0

我正在尝试从具有以下格式的文件中提取 2 个属性“lat”和“lon”:

<trkpt lat="38.8577288" lon="-9.0997973"/>
<trkpt lat="38.8576367" lon="-9.1000557"/>
<trkpt lat="38.8575259" lon="-9.1006374"/>
...

并获得以下输出:

-9.0997973,38.8577288
-9.1000557,38.8576367
-9.1006374,38.8575259

(是的,纬度/经度对是故意倒置的)

我对正则表达式了解不多,但是在网上环顾四周,这就是我能够实现的全部目标:

grep 'lat="[^"]*"' doc.txt | grep -no 'lat="[^"]*"'

output:
1:lat="38.8577288"
2:lat="38.8576367"
3:lat="38.8575259"

我不知道该怎么做...在此先感谢您的帮助

4

3 回答 3

1

使用 & (你不应该使用正则表达式来解析 HTML 或 XML!)

如果您还没有xmllint,请安装libxml2.

for i in {1..3}; do
    lat=$(xmllint --html --xpath "string(//trkpt[$i]/@lat)" file.xml)
    lon=$(xmllint --html --xpath "string(//trkpt[$i]/@lon)" file.xml)
    echo "$lon,$lat"
done < file.xml 2>/dev/null

--html(如果您的 XML 是完整有效的 XML,请删除)


请参阅RegEx 匹配打开的标签,XHTML 自包含标签除外

于 2013-10-19T19:56:49.417 回答
0

Assuming the format remains in this order, it'll only take one pass.

Find:                           Replace:
.+lat="(.+?)".*lon="(.+?)".+    $2,$1

The capture groups make sure to look for lat and lon in that order and then grab what's within quotes. It makes sure to involve the rest of the line so the replace discards it.

于 2013-10-19T17:36:16.407 回答
0

尝试像这样使用 Python:

python -c 'import re; open("dest", "w").write("\n".join([lat + "," + lon for lat, lon in re.findall("""<trkpt lat="([-0-9\.]+)" lon="([-0-9\.]+)"/>""", open("source").read())]))'

其中dest是包含逗号分隔的 lat 和 lon 值的输出文件的source路径,并且是包含 XML 样式标签的输入文件的路径。(这意味着在 linux shell 中使用。)请注意,我假设输入标签格式将非常一致。

那里的正则表达式是<trkpt lat="([-0-9\.]+)" lon="([-0-9\.]+)"/>.

如果您手边没有 linux shell,或者您更喜欢使用 python 脚本或以交互方式使用它,那么请使用以下方法来获得更少的单行方法:

#! /usr/bin/env python

# use the regex module
import re

# read in the file
in_file = open('source').read()

# Find matches using regex
matches = re.findall('<trkpt lat="([-0-9\.]+)" lon="([-0-9\.]+)"/>', in_file)

# make new file lines by combining lat and lon from matches
out_lines = [lat + ',' + lon for lat, lon in matches]

# convert array of strings to single string
out_lines = '\n'.join(out_lines)

# output to new file
open('dest', 'w').write(out_lines)
于 2013-10-19T19:37:08.410 回答