1

I'm on macOS. I have many directories at paths that looks like this:

./FirstName SecondName/A Multi Word Title/Contents/Index/files

I want to remove ALL the Index directories and their contents. I tried escaping the spaces with \ but that didn't work. If necessary I'm willing to make two passes, removing the files and then removing the directory.

1
  • I want to remove the directories and their contents but they are at the end of long strings with spaces. I tried using the rm command, attempting to escape the spaces but I get a No such file error message. If I manually type in the string, escaping the spaces, it works but it is a lot faster to just go into finder and delete them. I'm trying to use something like "find . -name index" and use that to remove the directories and their contents by piping it to "xargs rm." Commented Dec 15, 2022 at 22:23

3 Answers 3

1

If you truly want to remove all of them, you would use shell filename patterns:

rm -i -v -r ./*/*/Contents/Index

Check the rm man page for the meaning of the options.

1

To search for directories called Index in or below the current directory, and then to delete these, you would use find like so:

find . -depth -name Index -type d -exec rm -r {} \;

This does a depth-first search for the specific directories you are interested in and invokes rm -r on each of them in turn. We need to do a depth-first search (with -depth) as we might otherwise remove directories that haven't yet been visited by find, which would generate errors.

Use -path '*/Contents/Index' in place of the -name test if you need the Index directory to be a child directory of a Contents directory.

Using the zsh shell, or the bash shell with its globstar shell option set, you may also be able to use

rm -r ./**/Index/

or

rm -r ./**/Contents/Index/

This would call rm -r with a list of pathnames of directories called Index (assuming all the parts of the directory path are non-hidden, and assuming you're ok with also deleting directories symbolically linked via the name Index, and assuming the list of matching pathnames is not thousands of entries long). The trailing slash ensures that only directories are affected.

-1

I got the solution from another source and it worked.

find . -name directory* -print0 | xargs -0 rm -R
1
  • 1
    Note that the unquoted pattern directory* would be expanded before the find utility is called, and if it expands to more than one name, it would generate an error. In the zsh shell, it would generate an error by default if the pattern isn't matching anything. Also note that you need to attribute sources if you are copying code from elsewhere. Commented Dec 17, 2022 at 1:02

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.