passing bash arguments into sed to delete lines

£可爱£侵袭症+ 提交于 2020-02-22 15:33:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!