sed命令的奇怪行为

时间:2015-01-29 10:39:30

标签: bash sed solaris

有人可以解释sed的这种行为吗?

cat -bash-3.2# cat tmp7

echo "this is the song that never ends
yes, it goes on and on, my friend
some people started singing it
not knowing what it was
and they'll continue singing it forever
just because..." >

-bash-3.2# sed -n 's_.*some\(.*\)started.*_\1_p' tmp7

输出

people

-bash-3.2# cat tmp8
echo "this is the song that never endsyes, it goes on and on, my friendsome people started singing itnot knowing what it wasand they'll continue singing it foreverjust because..." >

sed -n 's_.*some\(.*\)started.*_\1_p' tmp8

什么都不输出

我希望第二个命令的输出应该等于第一个命令。

文件tmp7tmp8的内容是相同的,唯一的区别是tmp7包含换行符而tmp8不包含换行符。

更新

尝试使用不同版本的sed /usr/xpg4/bin/sed,获得理想的输出但警告sed: Missing newline at end of file tmp8.。我希望输出没有警告。

  /usr/xpg4/bin/sed -n 's_.*some\(.*\)started.*_\1_p' tmp8

   sed: Missing newline at end of file tmp8.
   people

1 个答案:

答案 0 :(得分:1)

Solaris默认sed忽略最后一行不破坏现有脚本,因为原始Unix实现中的新行需要终止一行。

GNU sed有一个更放松的行为,POSIX实现接受这个事实,但输出一个警告。您可以将stderr重定向到/ dev / null以忽略它。

/usr/xpg4/bin/sed -n 's_.*some\(.*\)started.*_\1_p' tmp8 2>/dev/null