在linux中使用grep将xml文件中包含的所有URL管道传输到单独的文件

时间:2014-06-06 10:06:30

标签: linux grep pipe

我有一个xml文件,如下所示。如何使用grep搜索此文件并将所有URL管道传输到由新行分隔的文件中。

<menus>
    <defaultMenu>
        <group>
            <menuItem name="Example one" url="http://www.google.com">
                <menuItem name="Example Two" url="http://www.yahoo.com" />
                <menuItem name="Example Three" url="http://www.bing.com" />
            </menuItem>
        </group>
    </defaultMenu>
</menus>

例如,我希望输出文件包含:

http://www.google.com
http://www.yahoo.com
http://www.bing.com

3 个答案:

答案 0 :(得分:1)

如果您想尝试gnu awk(由于RS)

awk -v RS="url" -F\" 'NR>1{print $2}' file >newfile
http://www.google.com
http://www.yahoo.com
http://www.bing.com

一个简单的awk

awk -F\" '/url/{print $4}' file
http://www.google.com
http://www.yahoo.com
http://www.bing.com

仅当格式始终相同时才有效。

答案 1 :(得分:0)

通过GNU sed,

$ sed -rn 's/^.*url="([^"]*)".*$/\1/p' file
http://www.google.com
http://www.yahoo.com
http://www.bing.com

通过GNU grep-P perl-regex )选项,

$ grep -oP '(?<=url=\")[^"]*' file
http://www.google.com
http://www.yahoo.com
http://www.bing.com

答案 2 :(得分:0)

假设您的文件sample.html运行以下命令以获取sample1.html文件中的网址

cat sample.html | grep -o url=\".*\" | cut -d "=" -f2 > sample1.html

如果你想删除引号,那么

cat sample.html | grep -o url=\".*\" | cut -d "=" -f2 | sed "s/\"//g" > sample1.html