2011-03-18 31 views
2

,如果我有文件SOME_FILE命名,与内容如下:猛砸,sed的:具有多文件内容替换模式

first line 
second line 
third line 

和内部脚本:

VAR1="first line\nsecond line\nthird line" 
VAR2="`cat some_file`" 

我希望VAR1和VAR2是相同,但它显然不是这样根据sed:

sed "s/^a/${VAR1}/" some_another_file # this is OK 
sed "s/^a/${VAR2}/" some_another_file # this fail with syntactic error 

我想,换行表示我有点不同,但我找不到如何让VAR2等于VAR1。

在此先感谢

+0

@ user665920:在编辑器中,然后按CTRL + K – Erik 2011-03-18 11:34:31

+0

请提交UNIX和GNU/Linux的选择代码/命令[unix.stackexchange.com](http://unix.stackexchange.com/)上相关的问题 – ierax 2011-03-18 11:37:42

回答

2

更改VAR1到:

VAR1=$(echo -e "first line\nsecond line\nthird line") 

然后对其进行测试:

$ [ "$VAR1" == "$VAR2" ] && echo equal 
equal 

更新:

为了让SED的工作,改变VAR2使其有“\ n”而不是换行符。

VAR2=$(sed ':a;N;$!ba;s/\n/\\n/g' some_file) 
sed "s/^a/${VAR2}/" file 
+0

好的,但我需要它的另一种方式。原始格式中的VAR1对于sed来说很好,但带有换行符的VAR2会导致语法错误。 – 2011-03-18 13:27:41

+0

然后将VAR2更改为:'VAR2 = $(sed':a; N; $!ba; s/\ n/\\ n/g'some_file)' – dogbane 2011-03-18 13:34:30

+0

就是这样!谢谢 – 2011-03-18 14:46:16

4

这将在文件中读取,并与它的内容替换行:

sed -e '/^a/{r some_file' -e 'd}' some_another_file