2012-08-13 38 views
1

之前添加多个保存在变量中的内衬字符串我一直在尝试很多方法,但没有运气。我有一个名为test.txt的文件,它有一些lorem ipsum和文本[staging:production]我只想添加几行,我保存在一个变量之前。查找一个字符串并在

如果你能解释我在哪里出错了,下面的任何内容都将非常感谢!

#!/bin/bash 

test="lala\ 
kjdsh" 

sed '/^#$/{N; /[staging: production]/ i \ 
<Location /cgis> \ 
</Location>\ 

}' ./test.txt 


sed -i -e 's/\[staging\: production\]/\$test/g' ./test.txt 
#sed -i 's/Lorem/beautiful/g' test.txt 

#awk -v data=$test '{A[NR]=$0}/\[staging\: production\]/{ print data }' test.txt > testfile.txt 

#read -a text <<<$(cat test.txt) 
#echo ${#text[@]} 
#for i in ${text[@]}; 
#do 
# echo -n $i; 
# sleep .2; 
#done 

#ed -s test.txt <<< $'/\[staging\: production\]/s/lalalala/g\nw' 

#awk -v data=$test '/\(/\[staging\: production\]\)/ { print data }' test.txt > testfile.txt 

# && mv testfile.txt test.txt 

#sed -i -e '/\(\[staging\: production\]\)/r/$test\1/g' test.txt 

#sed "/\(\[staging\: production\]\)/s//$test\1/g" test.txt 
+0

当您使用反斜杠作为续行字符时,行连接就像没有换行符一样。删除反斜线并保留换行符。 – 2012-08-13 23:37:22

回答

1
sed -i -e 's/\[staging\: production\]/\$test/g' ./test.txt 

不会起作用,因为里面燎报价BASH不会扩大\$test
因此,您不需要转义$

如果你想与变量$test的内容来代替做:

sed -i -e 's/\[staging: production\]/'$test'/g' ./test.txt 

你也不需要逃避:

要插入之前,你的模式工作对我来说是这样的:

sed -i -e '/\[staging: production\]/ i '$test'' ./test.txt 

但是为了保留我需要定义的变量内部的换行符:

test="lala\nkjdsh" 

请注意\n为换行符编码。

+0

这似乎是工作,但是,它不保留我的变量中的新行。 – gazzwi86 2012-08-13 15:31:05

+0

我不断收到sed:1:“/ \ [staging:production \ ...”:命令我希望\后面跟着文字 – gazzwi86 2012-08-13 15:37:39

+0

就像我说的 - 我必须通过'\ n'在变量内编码换行符 - 确实保留了我的环境中的换行符。 – 2012-08-13 15:39:18

0

尝试在Perl中,它似乎很好地工作:

perl -pe '{$rep="what\nnow"; s/(\[foo foo2\])/$rep$1/}' file 
0

这可能会为你工作(GNU SED):

test="lala\\         
kjdsh" 
sed '/\[staging: production\]/i\'"$test" test.txt 

注: \\在变量中,变量在sed命令中被"'s包围。

相关问题