0

I am kind of new to nerdy usage of Linux. I am playing around with pipelining at the moment. Can anyone tell me why this don't works:

ls | grep 2 | rm

(I tried to delete all files containing a 2 in their names) the ls | grep 2 part is working ( it returns all file names with a 2 in them ) why can't I pipeline these names now to rm to delete these files?

thanks four ur help in advance :)

Christian
  • 1,341
  • 1
  • 16
  • 35
  • Note that some commands will let you do this by appending a single dash as an argument, but [not all of them](http://unix.stackexchange.com/questions/41828/what-does-dash-at-the-end-of-a-command-mean), and `rm` doesn't happen to be one. But, for example, I can remove unnecessary packages on my Linux with `pacman -Qdqt | sudo pacman -Rns -`, which means list all unnecessary packages then pipe them to the package manager as which programs to remove. – Two-Bit Alchemist Apr 02 '14 at 15:49

1 Answers1

2

rm expects the file names as arguments whereas pipe sends the filenames to the standard input (stdin) of rm. You can instead do:

rm $(ls | grep 2)

to remove the files. This way the filenames are passed as arguments rather than to the standard input of rm.

I have used your commands to explain the problem. In general, you shouldn't parse the result of ls command.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Agreed. That's rather due to parsing ls command. Added the link for that. – P.P Apr 02 '14 at 15:44
  • Thanks for your answer. But how can I tell this? doesn't _stdin_-inputs and _arguments_ look kind of the same in a standard terminal usecase? – Christian Apr 03 '14 at 12:49
  • 1
    @ct2034 No. They are distinct. When you put some paramters *after* the command's name (*command arg1 arg2*) then they are arguments. In contrast, a pipe's output is *always* going to the stdin. Some commands are capable of interpreting stdin as arguments when passed with a specific parameter `-` e.g. `echo '#include' | gcc -E -`. But this is entirely upto each command's implementation whether they support this or not. – P.P Apr 03 '14 at 13:00