在 bash 脚本中执行 sed 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27051517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute sed command in a bash script
提问by Guille
I want to execute this comand in bash scripting.
我想在 bash 脚本中执行这个命令。
Code:
代码:
#!/bin/bash
line=39;
d=d; ## For delete line
`echo "sed '$line$d' /etc/passwd"`;
But when I execute, I got this error:
但是当我执行时,我收到了这个错误:
sed: -e expresion #1, character 1: unknow command <<'>>
I tried with echo "sed \'$line$d\' /etc/passwd"
;
我试过echo "sed \'$line$d\' /etc/passwd"
;
But same problem...
但是同样的问题...
回答by David C. Rankin
You need to insure when calling your variables that you do not prevent expansion by single-quoting
them. Now it is OK to use single-quotes
withindouble-quotes
, but be mindful. Also, though not required, when putting two variables back-to-back, it is better to use braces to insure against ambiguity. That said, your sed
command from a script works fine as:
您需要确保在调用变量时不会阻止single-quoting
它们的扩展。现在可以使用single-quotes
insidedouble-quotes
,但要注意。此外,虽然不是必需的,但在将两个变量背对背放置时,最好使用大括号来确保避免歧义。也就是说,您sed
来自脚本的命令可以正常工作:
sed -e "${line}${d}" /etc/passwd
Which will output /etc/passwd
to stdout
minus line $line
. To edit /etc/passwd
in place, use sed -i
这将输出/etc/passwd
到stdout
减号行$line
。要/etc/passwd
就地编辑,请使用sed -i
回答by ShellFish
To delete line 39 simply do:
要删除第 39 行,只需执行以下操作:
#!/bin/bash
line=39;
sed -i "${line}d" /etc/passwd
Sed will take the second argument as input file and the first as a command. The extra flag -i
will allow you to redirect the output immediately to the input file. Note that this is not the same as sed 'command' file > file
as this will result in an empty file.
sed 将第二个参数作为输入文件,第一个作为命令。额外的标志-i
将允许您立即将输出重定向到输入文件。请注意,这sed 'command' file > file
与这将导致空文件不同。
I also advise executing man sed
in your shell.
我还建议man sed
在你的 shell 中执行。
回答by NeronLeVelu
#!/bin/bash
# delete line 39 by editing inline via sed;
sed -i '39d' /etc/passwd
Keep it simple and add the comment if you want remember the sed action
如果您想记住 sed 操作,请保持简单并添加注释