【问题标题】:Trouble with piping through sed通过 sed 的管道问题
【发布时间】:2010-03-11 17:48:56
【问题描述】:

我无法通过 sed 进行管道传输。将输出通过管道传输到 sed 后,我无法将 sed 的输出通过管道传输到其他地方。

wget -r -nv http://127.0.0.1:3000/test.html

输出:

2010-03-12 04:41:48 URL:http://127.0.0.1:3000/test.html [99/99] -> "127.0.0.1:3000/test.html" [1]
2010-03-12 04:41:48 URL:http://127.0.0.1:3000/robots.txt [83/83] -> "127.0.0.1:3000/robots.txt" [1]
2010-03-12 04:41:48 URL:http://127.0.0.1:3000/shop [22818/22818] -> "127.0.0.1:3000/shop.29" [1]

我通过 sed 管道输出以获得一个干净的 URL 列表:

wget -r -nv http://127.0.0.1:3000/test.html 2>&1 | grep --line-buffered -v ERROR | sed 's/^.*URL:\([^ ]*\).*/\1/g'

输出:

http://127.0.0.1:3000/test.html
http://127.0.0.1:3000/robots.txt
http://127.0.0.1:3000/shop

我想将输出转储到文件中,所以我这样做:

wget -r -nv http://127.0.0.1:3000/test.html 2>&1 | grep --line-buffered -v ERROR | sed 's/^.*URL:\([^ ]*\).*/\1/g' > /tmp/DUMP_FILE

几秒钟后我中断了这个过程并检查了文件,但它是空的。

有趣的是,以下没有输出(与上面相同,但通过 cat 管道 sed 输出):

wget -r -nv http://127.0.0.1:3000/test.html 2>&1 | grep --line-buffered -v ERROR | sed 's/^.*URL:\([^ ]*\).*/\1/g' | cat

为什么我不能将 sed 的输出通过管道传输到像 cat 这样的另一个程序?

【问题讨论】:

  • sed 应该适用于管道,例如: echo "foo" | sed 's/foo/bar/g' >/tmp/foo 对我来说很好。将 -u 选项添加到 sed 会有所不同吗?或者,在检查文件之前尝试让该过程完成。 sed 可能只是对结果进行了过多的内部缓冲。

标签: bash shell sed pipe


【解决方案1】:

当 sed 写入另一个进程或文件时,它会缓冲数据。

尝试将--unbuffered 选项添加到 sed。

【讨论】:

    【解决方案2】:

    您也可以使用 awk。由于您的 URL 出现在字段 3 中,因此您可以使用 $3,也可以删除 grep。

    awk '!/ERROR/{sub("URL:","",$3);print $3}' file
    

    【讨论】:

    • 为什么不从今天开始呢? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多