路过的bash参数到sed的删除线 [英] passing bash arguments into sed to delete lines
问题描述
我试图写一个将采取所有发送给它的参数,并通过 SED $ C $推动他们一个
庆典
功能C>删除文件中的匹配参数的行。用例例如:
I'm trying to write a bash
function which will take all the arguments sent to it and push them through sed
to delete lines in a file that match the arguments. A use case example:
to_delete get the trash
我可以得到它几乎的工作是这样的:
I can get it to "almost" work like this:
function to_delete() { sed -i -e "/$@/d" /tmp/testfile; }
这样做的问题是,如果我发送一个命令行参数,将只工作:
The problem with this is it will only work if I send a single command line argument:
to_delete get
如果我发送一个以上返回这个错误:
If I send more than one it returns this error:
sed: 1: "/get": unterminated regular expression
如果我把周围的参数报价也将工作:
It will also work if I throw quotes around the arguments:
to_delete "get the trash"
但我宁愿没有这样做。
But I'd rather not have to do that.
这是如何得到这个工作任何想法?谢谢你。
Any ideas on how to get this working? Thanks.
推荐答案
您有$ @的问题是,它拓展了单独报价参数。
The problem you have with $@ is that it expands in separately quoted arguments.
您在理论上可以使用$ *来代替,因为这已经不是功能。
You could in theory use $* instead because this hasn't the feature.
BUT $ *将通过IFS的第一个字符(通常是一个空格)分隔的参数。
BUT $* will have the arguments separated by the first character of IFS (usually a space).
那么麻烦的是,如果你做一些事情:
So the trouble is if you do something:
to_delete foo bar baz
的格局将是这样的:
The pattern will look like:
/foo bar baz/d
(只有一个空格)。
(Only one space).
如果您使用的是加引号的参数这一切混乱避免,没有错。
All this mess is avoided if you use a quoted argument, nothing wrong with this.
这篇关于路过的bash参数到sed的删除线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!