[英]Sed command does not execute correctly when called from bash script and works fine when called from prompt
[英]Execute sed command in a bash script
我想在bash脚本中执行此命令。
码:
#!/bin/bash
line=39;
d=d; ## For delete line
`echo "sed '$line$d' /etc/passwd"`;
但是当我执行时,出现了这个错误:
sed: -e expresion #1, character 1: unknow command <<'>>
我尝试用echo "sed \\'$line$d\\' /etc/passwd"
;
但是同样的问题
您需要确保在调用变量时不会通过single-quoting
防止扩展。 现在可以在 double-quotes
使用single-quotes
double-quotes
,但要注意。 同样,尽管不是必需的,但当将两个变量背对背放置时,最好使用花括号来确保模棱两可。 也就是说,脚本中的sed
命令可以正常工作:
sed -e "${line}${d}" /etc/passwd
它将输出/etc/passwd
到stdout
减去$line
。 要就地编辑/etc/passwd
,请使用sed -i
要删除第39行,只需执行以下操作:
#!/bin/bash
line=39;
sed -i "${line}d" /etc/passwd
Sed将第二个参数作为输入文件,第一个作为命令。 额外的标志-i
将使您立即将输出重定向到输入文件。 请注意,这与sed 'command' file > file
因为这将导致sed 'command' file > file
为空。
我还建议在您的shell中执行man sed
。
#!/bin/bash
# delete line 39 by editing inline via sed;
sed -i '39d' /etc/passwd
保持简单并添加注释(如果您想记住sed操作)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.