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 $* will have the arguments separated by the first character of IFS (usually a space).
So the trouble is if you do something:
The pattern will look like:
(Only one space).
All this mess is avoided if you use a quoted argument, nothing wrong with this.