Unix 执行sed时不需要流中的换行符

Unix 执行sed时不需要流中的换行符,unix,sed,newline,Unix,Sed,Newline,我已经注意到了这一点,当我将一些不包含任何换行符的内容导入sed时,sed不会执行 例如,流包含一些文本(没有任何换行符) 命令: $echo -n "foo" | sed 's/foo/bar/' 什么也不输出 然而,如果我在流的末尾添加一个换行符,上面的命令将输出预期的替换: $echo "foo" | sed 's/foo/bar/' bar 我发现很多情况下我没有,也不想在流中使用换行符,但我仍然想运行sed替换 如果您有任何关于如何做到这一点的想法,我们将不胜感激。您所处的环境是什

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

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

命令:

$echo -n "foo" | sed 's/foo/bar/'
什么也不输出

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

$echo "foo" | sed 's/foo/bar/'
bar
我发现很多情况下我没有,也不想在流中使用换行符,但我仍然想运行sed替换


如果您有任何关于如何做到这一点的想法,我们将不胜感激。

您所处的环境是什么?您正在使用什么
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必须知道输入何时完成,因此它会查找文件结尾或行结尾,没有办法解决这个问题。

Nice one Daniel。我不确定我买的是哪一个,但我很确定它已经很旧了。我在我的cygwin中尝试了相同的命令,它起了作用,所以它一定是我在使用的服务器上使用的旧版本。但是,您的perl-pe命令工作得非常好,所以现在这将非常好。干得好。
$ 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.
$ cat test.txt | perl -pe 's/foo/bar/' | hexdump -C
00000000  62 61 72                                          |bar|
00000003