执行sed而不需要流中的换行符

时间:2011-05-05 23:42:40

标签: unix sed newline

当我将某些内容输入到不包含任何换行符的sed中时,已经注意到了这一点,sed没有执行。

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

foo

命令:

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

什么都不输出。

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

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

sed必须知道输入何时完成,因此它会查找End Of File或End Of Line,但实际上并没有办法解决这个问题。