Find the answer to your Linux question:
Results 1 to 4 of 4
Good afternoon everyone, I know that if you want to remove a single folder with a space in its name, you can do Code: rm -rf "Test Folder" I want ...
  1. #1
    Just Joined!
    Join Date
    Jan 2009
    Location
    Halifax, NS
    Posts
    19

    Removing folders with a space in name

    Good afternoon everyone,

    I know that if you want to remove a single folder with a space in its name, you can do

    Code:
    rm -rf "Test Folder"
    I want to remove all folders in a directory except specific ones. The problem is, it doesn't remove the folders with a space in their names.

    So if I have:

    Folder1
    Folder2
    Test Folder

    And I want to keep Folder1, but delete the others.

    Code:
    ls | grep -v Folder1 | xargs rm -rf
    That will delete Folder2, but not Test Folder because the command
    Code:
    rm -rf Test Folder
    doesn't work.

    Any help is appreciated and thanks for your time.

  2. #2
    Linux User
    Join Date
    Jun 2007
    Posts
    318
    As you mentioned in your first example the name has to be enclosed in quotes in order to access file or folder names with spaces in them. So you have to use quotes in the xargs command. You do this using the -I option as follows:

    Code:
    ls | grep -v Folder1 | xargs -I xxx rm -rfv "xxx"
    In this example the xxx will be replaced with the file/folder name. Since the name is now enclosed in quotes names with spaces in them will work.

  3. #3
    Just Joined!
    Join Date
    Jan 2009
    Location
    Halifax, NS
    Posts
    19
    Thanks for the reply vsemaska,

    I already found a solution though.

    I decided to use sed to replace the space with a backslash space.

    Code:
    ls | grep -v Folder1 | sed 's/ /\\ /' | xargs rm -rf
    This thread can be locked/closed now.

  4. #4
    Linux User
    Join Date
    May 2008
    Location
    NYC, moved from KS & MO
    Posts
    251
    Using just the command find, better solution maybe?
    Code:
    find . -mindepth 1 -type d -path ./Folder1 -o -print0 | xargs -0 rm -rf

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...