mike
mike

Reputation: 41

list files in terminal with spaces

ls -1 | grep -v images | xargs rm -r

That does not delete files that have spaces in them. How can I include them? Is there a way when I say ls that it displays with spaces escaped?

Upvotes: 2

Views: 1435

Answers (3)

sarnold
sarnold

Reputation: 104020

While you can make this work with ls(1), I think a better approach is to use find(1) instead:

find . \! -name '*images*' -exec rm -r {} \;

or

find . \! -name '*images*' -print0 | xargs -0 rm -r

I prefer the -print0 | xargs -0 approach when it works, because xargs(1) will spawn only as many rm(1) commands as is necessary. When you've only got 200 files, 200 executions or one execution won't make much difference, but if you had 10,000 files to delete, you'd really rather execute rm(1) only 200 or 500 times rather than all 10,000 times.

Upvotes: 2

Corey Henderson
Corey Henderson

Reputation: 7455

ls has the -Q option to quote them. You then simply can do this:

ls -Q | grep -v images | xargs rm -r

Upvotes: 4

miku
miku

Reputation: 188004

This should do the trick:

ls -1 | grep -v images | xargs -I {} rm -r "{}"

Upvotes: 1

Related Questions