Why doesn't rm work as I expect here?

徘徊边缘 提交于 2019-12-06 07:26:30

问题


I just want to do a simple thing. I got the following files in a directory:

AppInterface.h  baa  PEMsg.h  PluginInterface.h

Then I issue the command:

ls | grep -v ".h" | rm -rf

Much to my dismay, baa does not get deleted. But, this:

ls | grep -v ".h"

gives baa as I expect. So I guess the problem is with how rm takes input but I don't know why. Tried this both in csh and bash.


回答1:


rm doesn't take input from stdin so you can't pipe the list of files to it.

You need

 rm `ls | grep -v ".h"`

or

ls | grep -v ".h" | xargs rm -rf



回答2:


You want to use xargs:

ls | grep -v ".h" | xargs rm -rf



回答3:


rm doesn't read a list of files from stdin, which is why it's not working. You cannot pipe a list of file names to rm.

The correct way to do this would be

find . -maxdepth 1 -not -name '*.h' -exec rm -rf {} +

Using the versatile find utility. If you think this seems like a lot of work: that is the price of correctness. But, really, it isn't much worse once you're familiar with find.




回答4:


rm does not take its arguments from standard input. What you're probably looking for is command substitution (indicated by the backticks here), where the result of one command can be inserted into the arguments of another:

 rm -rf `ls | grep -v ".h"`


来源:https://stackoverflow.com/questions/4364907/why-doesnt-rm-work-as-i-expect-here

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