Elliott has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

OK, OK, I should know to use "chomp" by now! My failure to do so has created a directory on a remote server (a Linux box) containing 700 files with \n's in the filename. My FTP client won't delete them, nor will the simple Perl script I wrote to do it. Anyone got any bright ideas?

Ta!

Elliott

Replies are listed 'Best First'.
Re: \n in filenames
by Zaxo (Archbishop) on Oct 21, 2001 at 00:15 UTC
    perl -e 'unlink glob("*\n");'

    Update: A little explanation. A glob (distinct from a typeglob) is a kind of simplified regex for filenames. All unix shells use them, as does DOS in a further simplified form. Perl glob() follows the csh style of filename globbing in its argument, returning a list of all matching file names. The diamond operator applied to a bare string, as in print <*.txt>;, is another way to use them, but glob() is a better choice when interpolation of variables (or "\n") must be done.

    After Compline,
    Zaxo

      Thank you Zaxo. It worked. With the added bonus that the script deleted itself, of course (not the kind of script you want to leave lying around!)

      I don't really understand why it worked or why

      unlink "*\n"
      or just unlink "*"didn't work. I read the glob section in the Camel book and I'm not much wiser.

        This is because unlink is calling the underlying system call unlink which doesn't grok globs. You could do something like this:

        opendir( CUR, "whateverdir" ) or die "opendir: $!\n"; do { unlink or warn "unlink " . quotemeta($_) . ": $!\n"} for grep /\n$/, readdir( CUR ); closedir( CUR );

        And just for reference, a non-perl solution would be to use something like this (which uses a find-ism (-print0) which may not work everywhere).

        $ find -name "*\n" -print0 | xargs -0 rm
Re: \n in filenames
by jynx (Priest) on Oct 21, 2001 at 01:11 UTC

    Also,

    If you have account access to the machine, you can just use rm with the flags -ri. Namely:

    rm -ri <dirname>

    IIRC that's how i did it last time i had this problem :)

    jynx

Re: \n in filenames
by DamnDirtyApe (Curate) on Oct 21, 2001 at 06:37 UTC
    I made some test files with \n in the name, and
    rm -r `ls -1 | grep "\\\n"`
    deleted them all.