Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OS X: list and remove files with spaces

Tags:

bash

macos

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?

like image 749
Jian Avatar asked Jan 12 '13 05:01

Jian


People also ask

How do I delete all files by name on Mac?

Type "-name" followed by a space and then the file name pattern you would like to search for in quotes. To have the command delete files, finish off the command with the "-delete" flag.


2 Answers

[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
like image 83
Suku Avatar answered Oct 06 '22 17:10

Suku


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.

like image 31
waldyrious Avatar answered Oct 06 '22 18:10

waldyrious