Sed 命令不替换为文件中的多行
Sed command not replacing with multiline from file
我正在尝试用来自第二个文件 (file2) 的另一个文件 (file1) 替换文件 (file1) 中的一个 bloc。
File2 包含多行,比方说:
Print 1
Print 2
我正在使用这个命令:
file2="$(cat file2)"
sed -i "/Do_something/,/^}/c\
echo ${file2} " ${file1}
好处是它可以工作,但它在一行中替换了它。
我怎样才能用多行替换?
我试图直接放置变量但它不起作用,它只适用于 'echo'。
另外,如果我添加双引号,它不起作用。
您不需要在 shell 变量中读取 file2
。只需使用 r file
命令在 sed
中完成:
sed -e '/Do_something/,/^}/{/^}/!d; r file2' -e 'd;}' "$file1"
这可能适合您 (GNU sed):
sed -e '/Do_something/{:a;N;/^}/M!ba;r file2' -e 'd}' file1
用文件 2 的内容替换包含 Do_something
和另一行 }
之间的行。
N.B。只有在两个匹配项都匹配时才会进行替换,否则默认操作将保持文件不变,即 N
命令将到达 end-of-file 并打印模式 space 的内容。
在您可以做的每个 Unix 机器上的任何 shell 中使用任何 awk(未经测试,因为您没有提供我们可以测试的示例 input/output):
awk '
NR==FNR { new = (NR>1 ? new ORS : "") [=10=]; next }
/Do_something/ { f=1 }
f && /^}/ { [=10=]=new; f=0 }
!f
' file2 file1
以上假设如果您在输入中有 Do_something
那么您还将有一个后续的 }
因为您的问题中没有任何其他暗示。
如果您想用该命令的输出替换 file1
的内容,则只需在命令末尾添加 > tmp && mv tmp file1
。
我正在尝试用来自第二个文件 (file2) 的另一个文件 (file1) 替换文件 (file1) 中的一个 bloc。 File2 包含多行,比方说:
Print 1
Print 2
我正在使用这个命令:
file2="$(cat file2)"
sed -i "/Do_something/,/^}/c\
echo ${file2} " ${file1}
好处是它可以工作,但它在一行中替换了它。 我怎样才能用多行替换? 我试图直接放置变量但它不起作用,它只适用于 'echo'。 另外,如果我添加双引号,它不起作用。
您不需要在 shell 变量中读取 file2
。只需使用 r file
命令在 sed
中完成:
sed -e '/Do_something/,/^}/{/^}/!d; r file2' -e 'd;}' "$file1"
这可能适合您 (GNU sed):
sed -e '/Do_something/{:a;N;/^}/M!ba;r file2' -e 'd}' file1
用文件 2 的内容替换包含 Do_something
和另一行 }
之间的行。
N.B。只有在两个匹配项都匹配时才会进行替换,否则默认操作将保持文件不变,即 N
命令将到达 end-of-file 并打印模式 space 的内容。
在您可以做的每个 Unix 机器上的任何 shell 中使用任何 awk(未经测试,因为您没有提供我们可以测试的示例 input/output):
awk '
NR==FNR { new = (NR>1 ? new ORS : "") [=10=]; next }
/Do_something/ { f=1 }
f && /^}/ { [=10=]=new; f=0 }
!f
' file2 file1
以上假设如果您在输入中有 Do_something
那么您还将有一个后续的 }
因为您的问题中没有任何其他暗示。
如果您想用该命令的输出替换 file1
的内容,则只需在命令末尾添加 > tmp && mv tmp file1
。