linux - 如何根据某些字段对字符串进行排序

标签 linux bash unix

<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 是:

  1. " (-F"[\"]") 分割每一行
  2. 如果该行包含单词 "title" ($0~/title/),则它会将变量 title 设置为任何它在字段 6 (title=$6;) 中找到,如果您的“名称”包含空格,该字段可能会发生变化,因为我们正在拆分它,因此您可能不得不使用分隔符。
  3. 接下来,它将行的内容存储到数组 scenes 中,索引由存储在 title 中的数字设置({场景[标题]=场景[标题]$0"\n"})
  4. 一旦处理完文件,它就会将 PROCINFO["sorted_in"] 设置为 @ind_num_asc,这会告诉 awk 使用索引遍历数组,同时强制用作数字的索引 (END{PROCINFO["sorted_in"]="@ind_num_asc")
  5. 然后我们遍历数组并打印每个元素 (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/

相关文章:

linux - 使用 xdotool 刷新桌面

c++ - 如何从 system() 获取 shell 输出?

linux - 在启用 NX (DEP) 和 ASLR 的 x86-64 上利用基于字符串的溢出

c++ - 使用 Qt (Ubuntu 14.04) 编译 qt-dab 时出错

python - 从 bash 运行 python 脚本到终端未运行

linux - Apache 中的 .htaccess 不工作

mongodb - 来自 mongod 4.4 命令的不可读终端日志

PHP 或 shell : How to randomize a list without back to back repeats?

linux - 在系统调用中是否保存了硬件和软件上下文?

linux - Linux 如何确定设备类别?