shell脚本:使用sed将新行插入文件

时间:2013-07-02 21:31:05

标签: shell insert sed newline

目前,文件a.txt包含:

#define ABC

我想将a.txt更改为:

#define ABC
#define DEF

我试过

sed 's/#define ABC/#define ABC&\n#define DEF/g' a.txt > tmp/test.txt
mv tmp/test.txt > a.txt

但它改为给我#define ABC#define ABCn#define EDF。在线尝试了多种解决方案,但它无法正常工作。我的解决方案有什么问题?感谢!!!

使用Solaris 11

5 个答案:

答案 0 :(得分:3)

尝试类似:

$ echo '#define ABC' | sed '/ABC$/ a\
> #define DEF'
#define ABC
#define DEF

注意:在Oracle Solaris 10 9/10上测试s10s_u9wos_14a SPARC

答案 1 :(得分:2)

GNU代码


$echo #define ABC|sed 's/.*/&\n#define DEF/'
#define ABC
#define DEF

答案 2 :(得分:2)

除了你的'&'是问题。

试试这个

sed 's/#define ABC/#define ABC \n#define DEF/g' a.txt

#define ABC
#define DEF

我在我的unix盒子里测试过,它工作正常

所以你的最终解决方案应该是这样的

sed 's/#define ABC/#define ABC \n#define DEF/g' a.txt
a.txt > tmp/test.txt
mv tmp/test.txt > a.txt

答案 3 :(得分:1)

引用链接的第二个示例是您的解决方案

< a.txt sed "/ABC$/a \\
#define DEF
"

将从a.txt生成

#define ABC

输出

#define ABC
#define DEF

或上述链接中的第5个例子

< a.txt sed "/ABC$/s/$/\\
#define DEF/"

所以,请阅读!

答案 4 :(得分:0)

标准Solaris sed需要如下设置换行符:

echo "#define ABC" | sed 's/#define ABC/#define ABC\
#define DEF/'

\ n或\ x0A在SunOS上不起作用。

相关问题