linux - 查找一个字符串并添加之前保存在变量中的多行字符串

标签 linux bash shell sed awk

我已经尝试了很多方法,但都没有成功。我有一个名为 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/

相关文章:

html - 我如何从 cgi-bin 提供 HTML?

linux - 在 shell 脚本中使用相同的命令,只是带有前缀

具有日志功能的 c Pipes shell 守护进程无法正常工作

html - 通过 HTML 对象在 Linux 上播放 *.au 文件

linux - 在 debian 上每隔一段时间运行命令

linux - 使用 sed 从变量中删除模式

Python 通信 vs shell=True

PHP Interactive - 从命令行加载文件

linux - CentOS - 仅显示 1 行文件

linux - __connect_no_cancel block 和服务器获取数据乱序