<scene name="scene_1_Overview" title="1 Overview" onstart="" thumburl="panos/1_Overview.tiles/thumb.jpg" lat="" lng="" heading="">
abc
</scene>
<scene name="scene_1_Overview" title="10 Overview" onstart="" thumburl="panos/1_Overview.tiles/thumb.jpg" lat="" lng="" heading="">
abc
</scene>
<scene name="scene_10_Room_Balcony_View" title="2 Room Balcony View" onstart="" thumburl="panos/10_Room_Balcony_View.tiles/thumb.jpg" lat="" lng="" heading="">
abc
def
</scene>
说我有如上这样的一个XML文件。
现在我需要根据后面跟着 title=
的数字顺序制作这三个元素。 ,分别是 1、10 和 2。
我正在考虑使用 bash 脚本来执行此操作。
我可以使用类似 awk '{print $3}' test | awk -F "\"" '{print $2}'
的东西得到三个数字,但我不知道如何从每个 <scene
中读取多行至 </scene>
, 使它们有序并覆盖它们。
最佳答案
我认为在 awk
中这样做并不是最好的主意,但我知道被困在一个无法安装任何东西的盒子上是什么感觉。如果您坚持使用它,那么像下面的 awk 脚本这样的东西应该会让您大致了解。
awk -F"[\" ]" '$0~/title/{title=$6} {scene[title]=scene[title]$0"\n"} END{PROCINFO["sorted_in"]="@ind_num_asc"; for (title in scene) {print scene[title]}}' inFile
这里的 awk 是:
- 用
"
或(
-F"[\"]"
) 分割每一行 - 如果该行包含单词
"title"
($0~/title/
),则它会将变量title
设置为任何它在字段 6 (title=$6;
) 中找到,如果您的“名称”包含空格,该字段可能会发生变化,因为我们正在拆分它,因此您可能不得不使用分隔符。 - 接下来,它将行的内容存储到数组
scenes
中,索引由存储在title
中的数字设置({场景[标题]=场景[标题]$0"\n"}
) - 一旦处理完文件,它就会将
PROCINFO["sorted_in"]
设置为@ind_num_asc
,这会告诉 awk 使用索引遍历数组,同时强制用作数字的索引(END{PROCINFO["sorted_in"]="@ind_num_asc"
) - 然后我们遍历数组并打印每个元素 (
for (title in scene) {print scene[title]}
)
最小化一点:
awk -F"[\" ]" '$0~/title/{t=$6}{s[t]=s[t]$0"\n"}END{PROCINFO["sorted_in"]="@ind_num_asc";for(t in s)print s[t]}' inFile
关于linux - 如何根据某些字段对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44113955/