我已经尝试了很多方法,但都没有成功。我有一个名为 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
最佳答案
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
以对换行符进行编码。
关于linux - 查找一个字符串并添加之前保存在变量中的多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936890/