Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.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
Sed命令:替换文本文件(bash)中的节_Bash_Text_Sed - Fatal编程技术网

Sed命令:替换文本文件(bash)中的节

Sed命令:替换文本文件(bash)中的节,bash,text,sed,Bash,Text,Sed,我想用临时文件中的section1替换输入文件中的section1 我的inputfile包含 section1 a1 section2 a2 section3 a1 以下是临时文件的上下文: section1 a1,b2 我当前的尝试如下所示: sed -i "/$section/,//{/$section/{p;r $temporaryfile};//p;d}" $Inputfile 我希望看到以下输出: section1 a1,b2 section2 a2 section3 a1

我想用临时文件中的section1替换输入文件中的section1

我的
inputfile
包含

section1
a1
section2
a2
section3
a1
以下是
临时文件的上下文:

section1
a1,b2
我当前的尝试如下所示:

 sed -i "/$section/,//{/$section/{p;r $temporaryfile};//p;d}"  $Inputfile
我希望看到以下输出:

section1
a1,b2
section2
a2
section3
a1
但是,我的代码只会给我一条错误消息:

sed: -e expression #1, char 0: unmatched `{'
sed: -e expression #1, char 0: unmatched `{'

引用的

sed仅适用于s/old/new,仅此而已。对于其他任何东西,只需使用awk以实现简单性、健壮性、可移植性、效率等:

$ cat tst.awk
NR%2 { name = $0; next }
NR==FNR { val[name] = $0; next }
{ print name ORS (name in val? val[name] : $0) }

$ awk -f tst.awk temporaryfile Inputfile
section1
a1,b2
section2
a2
section3
a1

sed代表s/旧/新,仅此而已。对于其他任何东西,只需使用awk以实现简单性、健壮性、可移植性、效率等:

$ cat tst.awk
NR%2 { name = $0; next }
NR==FNR { val[name] = $0; next }
{ print name ORS (name in val? val[name] : $0) }

$ awk -f tst.awk temporaryfile Inputfile
section1
a1,b2
section2
a2
section3
a1

许多
sed
方言要求大括号是单独的“命令”。因此,在最后一个右大括号之前需要一个分号

另外,
r
后面的参数没有任何引号,因此需要显式终止它,例如使用换行符

最后,作为一个小优化,no-op-empty regex
/
没有任何用途;你可以不说

sed "/$section/,//{/$section/{p;r $temporaryfile
};p;d;}"

一些shell初学者惊讶地发现引号中可以有一个换行符,但事实上这是完全正常的。

许多
sed
方言要求大括号是单独的“命令”。因此,在最后一个右大括号之前需要一个分号

另外,
r
后面的参数没有任何引号,因此需要显式终止它,例如使用换行符

最后,作为一个小优化,no-op-empty regex
/
没有任何用途;你可以不说

sed "/$section/,//{/$section/{p;r $temporaryfile
};p;d;}"
一些shell初学者对引号中可以有一个换行符感到震惊,但事实上这是完全正常的