Search code examples
shellscriptingsolaris

rm command to be use with xargs to exclude some folders having space in the name


In one directory I have around 50 files and folders that includes some folders with space in their names. I want to delete some folders using ls, grep and xargs command but not able to delete the folders with space in their names and shows exception. Can anyone help? Using a Solaris OS. I tried below for deleting everything except $files

ls | grep -v "$files" | xargs rm

and when I tried below command it deletes everything including $files which I dont want.

ls | grep -v "$files" | xargs rm --*\ *


Solution

  • Without using non-standard extensions, and assuming your shell implements while read ..., this also should work:

    ls | grep -v "$files" | while read filename; do
        rm "$filename"
    done
    

    The quotes around $filename are critical. Without the quotes, the argument will be split on any spaces that may be in the name.

    Note also that won't delete a directory - as others have mentioned, you need rm -r - or rmdir - to do that. But rm -r will delete a directory and everything in it. rmdir by default won't delete a non-empty directory.

    You probably should run a test first with something like

    ls | grep -v "$files" | while read filename; do
        ls -ld "$filename"
    done
    

    Use the -ld options to ls to be sure you're getting the correct file, and also to not list directory contents if the file name passed happens to be a directory.