问题
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.
回答1:
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 $* 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.
回答2:
Quotes is a good option. If you still insist in having this, one option would be something like this:
function to_delete() { sed -i -e "/`echo $@`/d" /tmp/testfile; }
The problem was that $@
get separated into several arguments. This have several problems, though, for instance, the search term having the character '/
', for instance.
来源:https://stackoverflow.com/questions/4108850/passing-bash-arguments-into-sed-to-delete-lines