Jian
Jian

Reputation: 11080

OS X: list and remove files with spaces

I'd like to do this in OS X:

ls -rt | xargs rm -i

However, rm is choking on the fact that some of the files have whitespaces.

I mention OS X because BSD's version of ls does not have a -Q flag.

Is there a way to do this without having to use find -print0?

Upvotes: 7

Views: 2728

Answers (5)

Suku
Suku

Reputation: 3880

[sgeorge@sgeorge-ld staCK]$ touch "file name"{1..5}.txt
[sgeorge@sgeorge-ld staCK]$ ls -1
file name1.txt
file name2.txt
file name3.txt
file name4.txt
file name5.txt
[sgeorge@sgeorge-ld staCK]$ ls -rt | xargs -I {} rm -v {}
removed `file name5.txt'
removed `file name4.txt'
removed `file name3.txt'
removed `file name2.txt'
removed `file name1.txt'

OR

[sgeorge@sgeorge-ld staCK]$ ls -1
file a
file b
file c
file d

[sgeorge@sgeorge-ld staCK]$ OLDIFS=$IFS; IFS=$'\n'; for i in `ls -1`; do rm -i $i; done; IFS=$OLDIFS
rm: remove regular empty file `file a'? y
rm: remove regular empty file `file b'? y
rm: remove regular empty file `file c'? y
rm: remove regular empty file `file d'? y

Upvotes: 5

waldyrious
waldyrious

Reputation: 3844

You have two options. You can either call xargs with the -0 option, which splits the input into arguments using NUL characters (\0) as delimiters:

ls -rt | tr '\n' '\0' | xargs -0 rm -i

or you can use the -I option to split the input on newlines only (\n) and call the desired command once for each line of the input:

ls -rt | xargs -I_ rm -i _

The difference is that the first version only calls rm once, with all the arguments provided as a single list, while the second one calls rm individually for each line in the input.

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247162

If you want to delete all files, what's wrong with rm -i *?

Don't parse ls

Upvotes: 1

Zombo
Zombo

Reputation: 1

Try this

while read -u 3
do
  rm -i "$REPLY"
done 3< <(ls -rt)

Upvotes: 0

jeffmurphy
jeffmurphy

Reputation: 446

Just have find delete it for you.

find . -print -depth 1 -exec rm -i {} \;

It's more flexible, should be ok with spaces.

Upvotes: 1

Related Questions