bash 将 sed 与命令行参数一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14885535/
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
Using sed with command line argument?
提问by Dude
I need to run a sed command like this as part of a shell script
我需要运行像这样的 sed 命令作为 shell 脚本的一部分
sed 's/brad/pitt/g'
I am supposed to provide brad as a command line argument and run a command like this
我应该提供 brad 作为命令行参数并运行这样的命令
sed s//pitt/g
While this command is working, what I would like to know is how can I do this command without removing the quotes, since I might have some content in the replacement string which needs the quotes.
虽然此命令正在运行,但我想知道的是如何在不删除引号的情况下执行此命令,因为我可能在替换字符串中有一些需要引号的内容。
I am not so confident with the quotes and that is why I want to see how things will work with a little tweaking?
我对引号不太有信心,这就是为什么我想看看稍微调整一下会如何工作?
回答by Karoly Horvath
You can sed "s/$1/pitt/g"
or sed 's/'$1'/pitt/g'
你可以sed "s/$1/pitt/g"
或sed 's/'$1'/pitt/g'
or, if the command line argument is not a simple word, sed 's/'"$1"'/pitt/g'
.
或者,如果命令行参数不是简单的单词,则sed 's/'"$1"'/pitt/g'
.
回答by Joshua Clayton
There are two ways you can do it:
有两种方法可以做到:
1) use double quotes
1)使用双引号
sed "s//pitt/g"
2) construct the command as a string and run it with eval
2) 将命令构造为字符串并使用 eval 运行它
SEDCMD="s//pitt/g"
eval sed $SEDCMD
The eval method works and is very flexible, but is considered dangerous, because it is vulnerable to code injection. If you don't trust your inputs, don't use #2
eval 方法有效并且非常灵活,但被认为是危险的,因为它容易受到代码注入的影响。如果您不相信自己的输入,请不要使用 #2
UPDATE: The comments are right, there is no benefit to using eval (I used to use eval with sed this way all the time, and I'm not sure why....) building sed strings for later use, however, is powerful: so I'll add a new 3) and leave 2 for folks to mock
更新:评论是对的,使用 eval 没有任何好处(我曾经一直以这种方式将 eval 与 sed 一起使用,我不确定为什么....)构建 sed 字符串供以后使用,但是,是强大:所以我会添加一个新的 3) 并留下 2 供人们嘲笑
3) construct the command as a string and then run 1 or more of them
3) 将命令构造为字符串,然后运行其中的 1 个或多个
FOO='s/\(.*\)bar/baz/'
BAR="s//pitt/g"
sed -e $BAR -e $FOO <infile >outfile