sed拆分单行文件并处理结果行

时间:2011-05-21 21:35:33

标签: linux unix sed newline

我在一行中有一个XML提要(this),所以要提取我需要的数据,我可以这样做:

sed -r 's:<([^>]+)>([^<]+)</\1>:&\n: g' feed | sed -nr '
    /<item>/, $ s:.*<(title|link|description)>([^<]+)</\1>.*:\2: p'

因为我找不到第一次sed调用处理结果作为不同行的方法。

有什么建议吗?

我的目标是在一次sed电话中获取我需要的所有数据

3 个答案:

答案 0 :(得分:2)

sed -rn -e 's|>[[:space:]]*<|>\n<|g
/^<title>/ { bx }
/^<description>/ { b x }
/^<link>/ { bx }
D
:x
s|<([^>]*)>([^\n]*)</\1>|\1=\2|;
P
D' rss.xml

新问题的新答案。现在有分支并输出所有三个信息块。

答案 1 :(得分:1)

sed -rn -e 's|>[[:space:]]*<|>\n<|g   # Insert newlines before each element
/^[^<]/ D                             # If not starting with <, delete until 1st \n and restart
/^<[^t]/ D                            # If not starting with <t, ""
/^<t[^i]/ D                           # If not starting with <ti, ""
/^<ti[^t]/ D
/^<tit[^l]/ D
/^<titl[^e]/ D
/^<title[^>]/ D                       # If not starting with <title>, delete until 1st \n and restart
s|^<title>||                          # Delete <title>
s|</title>[^\n]*||                    # Delete </title> and everything after it until the newline
P                                     # Print everything up to the first newline
D' rss.xml                            # Delete everything up to the first newline and restart

通过“重启”我的意思是回到sed脚本的顶部并假装我们只是阅读剩下的内容。

我学到了很多关于sed写这篇文章的知识。但是,毫无疑问,你真的应该在perl中这样做(或者如果你是老学校,那就是awk)。

在perl中,这将是perl -pe 's%.*?<title>(.*?)</title>(?:.*?(?=<title>)|.*)%$1\n%g' rss.xml

这基本上利用了最小匹配(。*?非贪婪,它将匹配尽可能少的字符数)。最后的积极前瞻是,我可以用一个表达式来完成,同时仍然删除最后的所有内容。不止一种方式......

如果您需要使用此xml文件中的多个标签,它可能仍然可能,但可能涉及分支等。

答案 2 :(得分:0)

这个怎么样:

sed -nr 's|>[[:space:]]*<|>\n<|g
    h
    /^<(title|link|description)>/ {
        s:<([^>]+)>([^<]+)</\1>:\2: P
    }
    g
    D
    ' feed
相关问题