I'm trying to pipe
grep output to
rm, but it outputs useless stuff. Is any switch required for
rm? Or can
rm can be provided a regexp directly?
ls | grep '^\[Daruchini'| rm
rm: missing operand Try `rm --help' for more information.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
You need to use
xargs to turn standard input into arguments for
$ ls | grep '^Dar' | xargs rm
(Beware of special characters in filenames; with GNU grep, you might prefer
$ ls | grep -Z '^Dar' | xargs -0 rm
Also, while the shell doesn't use regexps, that's a simple pattern:
$ rm Dar*
(meanwhile, I think I need more sleep.)
Here, it's very simple to get the shell to filter the files you want. Note that it's the shell that's expanding the pattern
Dar*, not the
rm command. The pattern expansion performed by the shell is called globbing.
In more complex cases, look up the
If you want to delimit the output of
grep by newlines rather than whitespace, you can specify that to
xargs via the
$ ls | grep '^Dar' | xargs -d '\n' rm
(as described in this question)
On Catalina 10.15.3, with zsh, the way I found to deal with newlines and white spaces was:
sudo find / | grep -i 'yourString' | tr '\n' '\0' | xargs -0 -n1 rm -r
In other words, by translating new lines with no space (tr \n to \0) before removing it with "rm -0".
Also, I always use 'find'+'grep -i' because 'find -iname' sometimes doesn't output anything.
One last note: it finds and remove files and folders that matches 'yourString'. For files only, specify "find -type f", and then the option "-r" for rm is useless.