【问题标题】:Execute sed without requiring a newline character in stream执行 sed 而不需要流中的换行符
【发布时间】:2011-05-05 23:42:39
【问题描述】:

当我将一些不包含任何换行符的内容导入 sed 时,我已经注意到了几次,sed 不会执行。

例如,一个流包含一些文本(没有任何换行符)

foo

命令:

$echo -n "foo" | sed 's/foo/bar/'

什么都不输出。

而如果我在流的末尾添加一个换行符,上面的命令将输出预期的替换:

$echo "foo" | sed 's/foo/bar/'
bar

我发现了很多我没有的情况,并且我真的不想在我的流中使用换行符,但我仍然想运行 sed 替换。

任何想法如何做到这一点将不胜感激。

【问题讨论】:

    标签: unix sed newline


    【解决方案1】:

    你在什么环境?你用的是什么sed

    因为在这里,我有一个更好的sed

    $ echo -n foo | sed 's/foo/bar/'
    bar$ 
    $ echo -n foo > test.txt
    $ hexdump -C test.txt
    00000000  66 6f 6f                                          |foo|
    00000003
    $ cat test.txt | sed 's/foo/bar/'
    bar$ cat test.txt | sed 's/foo/bar/' | hexdump -C
    00000000  62 61 72                                          |bar|
    00000003
    $ sed --version
    GNU sed version 4.2.1
    Copyright (C) 2009 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE,
    to the extent permitted by law.
    
    GNU sed home page: <http://www.gnu.org/software/sed/>.
    General help using GNU software: <http://www.gnu.org/gethelp/>.
    E-mail bug reports to: <bug-gnu-utils@gnu.org>.
    Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.
    

    请注意,获得更好的sed 的一种方法是将其输入为perl -pe,如下所示:

    $ cat test.txt | perl -pe 's/foo/bar/' | hexdump -C
    00000000  62 61 72                                          |bar|
    00000003
    

    【讨论】:

    • 不错的丹尼尔。我不确定我有哪个 sed,但我很确定它已经很旧了。我在我的 cygwin 中尝试了相同的命令并且它有效,所以它必须是我正在使用的服务器上的旧版本。但是,您的 perl -pe 命令可以完美运行,因此现在效果很好。干得好。
    【解决方案2】:

    sed 必须知道输入何时完成,因此它会查找文件结尾或行尾,实际上没有办法解决这个问题..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-14
      • 2015-04-23
      • 1970-01-01
      • 2014-01-23
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多