[colug-432] scripting question: Spaces in Filenames Require Careful Quoting

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Sat May 7 23:03:50 EDT 2016


On Sat, 7 May 2016 22:31:06 -0400, Johnathon Scott <js573712 at ohio.edu> wrote:

> I am having difficulty understanding how to pass values to rm.  I want
> to delete files that match a specific criterion.  I recently acquired an
> os x machine and iTunes has doubled a significant portion of my
> library.  But fortunately, the duplicates are easy to identify, they all
> look like "foo 2.(mp3|m4a)".
> 
> What I have right now is "ls -R | grep "\ 2\.mp3" | rm -v".

There are multiple correct solutions.

Spaces in names cause much grief in *nix land, especially for novices.
However, spaces can be handled safely. Once you learn how to do that,
establish a habit of having the discipline to _always_ do it safely.

Learn the importance of quoting and how one quotes.
Single quotes work differently than double quotes.

Here are some commands to explore.

find -name ' 2.mp3' -exec rm -v {} \;
find -name ' 2.mp3' -print0 | xargs -0 rm -v
find | grep ' 2[.]mp3$' | xargs rm -v
find | grep ' 2[.]mp3$' | while read f; do rm -v "$f";done

Study every character of "$f" in that last line, including the quotes.
You must master that.

The following is dangerous because of the lack of quotes.
Do not execute it, except on a sacrificial machine.
What would happen if a filename was
"/mymusic/whos/on/first /etc/passwd 2.mp3"?

#do no do this command find /mymusic/whos/on/ | grep ' 2[.]mp3$' | while read f; do rm -v $f;done

By the way, I expect that ls -R is feeble for what you want.


More information about the colug-432 mailing list