问题
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