0

I have a group of files I'd like to remove at once.

ls | egrep \^New

The output is as expected,

New 1
New 2
New 3

but continuing the pipe with

| xargs -L rm

attempts to remove the input as space-delimited:

rm: New: No such file or directory
rm: 1: No such file or directory

What am I missing?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
erythraios
  • 3
  • 1
  • 2

2 Answers2

4

Don’t parse ls. This should do the trick:

rm New*

Your approach is failing because xargs splits arguments up on whitespace by default, so it runs rm on New, 1, New, 2 etc. You could work around that by splitting on newlines, but that won’t work with filenames containing newlines.

Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
1

Yes you're right, xargs is breaking up the file names at the spaces. If you're using GNU xargs you can have it use a newline as the delimiter with the -d option. Example:

ls | egrep \^New | xargs -d '\n' rm

Satō Katsura
  • 13,138
  • 2
  • 31
  • 48
David Birks
  • 440
  • 5
  • 6
  • I don't think `xargs` has a `-d` option. – erythraios Oct 17 '17 at 16:42
  • @erythraios `xargs -d` is [not POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html). But the [`xargs`](https://linux.die.net/man/1/xargs) provided by [GNU Findutils](https://www.gnu.org/software/findutils/), which is present in GNU/Linux systems, [does support it](https://www.gnu.org/software/findutils/manual/html_mono/find.html#xargs-options). – Eliah Kagan Oct 17 '17 at 16:47
  • Either used `rm New*` or use `find . -type f -name "New*" -print0 |xargs -0 -r rm` .. both handle special char correctly (the later is recursive and it's very powerful) – Franklin Piat Oct 17 '17 at 18:26