Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 通过sed用多行变量替换字符串中的关键字_Bash_Variables_Sed_Replace_Multiline - Fatal编程技术网

Bash 通过sed用多行变量替换字符串中的关键字

Bash 通过sed用多行变量替换字符串中的关键字,bash,variables,sed,replace,multiline,Bash,Variables,Sed,Replace,Multiline,注:以下问题与相关,但问题的焦点和输入变量的格式不同(即多行文件的内容)。因此,正确的解决方案也可能不同 似乎只要所述变量包含显式换行符(\n),就可以通过sed将字符串中的关键字替换为多行变量 但是,当我在文本编辑器中打开文件file并用换行符替换换行符时,用sed替换会失败 当输入变量没有显式换行符时,如何更改sed命令以执行所需的替换?Introduction/Setup sed不一定是此特定作业的合适工具。考虑下面的选项——每个样本都期望下面的设置: # Run this before

注:以下问题与相关,但问题的焦点和输入变量的格式不同(即多行文件的内容)。因此,正确的解决方案也可能不同

似乎只要所述变量包含显式换行符(
\n
),就可以通过
sed
将字符串中的关键字替换为多行变量

但是,当我在文本编辑器中打开文件
file
并用换行符替换换行符时,用sed替换会失败

当输入变量没有显式换行符时,如何更改sed命令以执行所需的替换?

Introduction/Setup
sed
不一定是此特定作业的合适工具。考虑下面的选项——每个样本都期望下面的设置:

# Run this before testing any of the code below
source='bar'
target='This string contains a target: <bar>'
solution='This has
multiple lines
and /slashes/ in the text'

Perl一行程序作为
sed
替代方案 <>对于较长的输入字符串,其中shell的内置匹配不合适,您也可以考虑Perl一个内衬,如:


in=“$source”out=“$solution”perl-pe的/\Q$ENV{“in”}/$ENV{“out”}/g”除了基本的文本替换之外,不要使用sed,使用awk或perl来接受变量作为参数,这样可以省去很多麻烦。@123是的,但是上面的文本替换对我来说是相当基本的。问题是换行符和换行符的处理方式不同,我不知道如何避免这个问题。sed不支持替换文字换行符,因此显然它不够基本。感谢详细的回答。您让我相信Bash的内置参数扩展是这里使用的合适工具。
# Newline character was manually replaced with linebreak in texteditor.
$ solution=$(cat file)
$ echo "$solution"
qux
quux
$ echo $target | sed -e "s|bar|$solution|"
sed: -e expression #1, char 9: unterminated `s' command
# Run this before testing any of the code below
source='bar'
target='This string contains a target: <bar>'
solution='This has
multiple lines
and /slashes/ in the text'
result=${target//$source/$solution}
echo "$result"
in="$source" out="$solution" perl -pe 's/\Q$ENV{"in"}/$ENV{"out"}/g' <<<"$target"