如何将变量传递给sed“ $(sed -n'/ 110600002019 / ='tmuser.cf | tail -n 1)”'s / 110600002019/120700002019 /'tmuser.cf

我希望按如下所示传递变量。 a = 110600002019 b = 120700002019

  sed "$(sed -n '/$a/ =' tmuser.cf | tail -n 1)" 's/$a /$b/' tmuser.cf
a546335402 回答:如何将变量传递给sed“ $(sed -n'/ 110600002019 / ='tmuser.cf | tail -n 1)”'s / 110600002019/120700002019 /'tmuser.cf

sed "$(sed -n "/$a/ =" tmuser.cf | tail -n 1) s/$a /$b/" tmuser.cf

为我工作。我做了一个小的测试文件

cat tmuser.cf
a
110600002019
b
c
120700002019

不确定120700002019,所以我将其放入文件中。

上面脚本的输出是

a
120700002019
b
c
120700002019

请注意,通过将命令包装为

,您可以在调试此类问题方面学到很多东西
set -vx ; ... your cmnds .... ; set +vx

这样做产生了第一个线索

sed "$(sed -n '/$a/ =' tmuser.cf | tail -n 1)" 's/$a /$b/' tmuser.cf
1 >sed -n '/$a/ =' tmuser.cf
1 >tail -n 1
1 >sed '' 's/$a /$b/' tmuser.cf
sed: s/$a /$b/: cannot open [No such file or directory]    
a
110600002019
b
c
120700002019

没有任何变量被其值替换。您需要使用dbl引号,以便可以替换变量。

错误消息

sed: s/$a /$b/: cannot open [No such file or directory]  

告诉我们sed认为s/$a /$b/是文件名,而不是命令。所有命令都必须显示为将它们传递给sed的外壳程序的一个不间断字符串,因此请注意我的更改方式

...| tail -n 1)" 's/$a /$b/'...

...|  tail -n 1)  s/$a /$b/"....

IHTH

本文链接:https://www.f2er.com/3152090.html

大家都在问