Home > OS >  Bash delete a file excluding under a directory or subdirectory containing certain name pattern
Bash delete a file excluding under a directory or subdirectory containing certain name pattern

Time:02-24

The file structure:

|-- ./a
|   |-- ./a/b
|   |   `-- ./a/b/file.json
|   `-- ./a/file.json
|-- ./file.json
|-- ./folder
|   `-- ./folder/file.json
|-- ./guides
|   `-- ./guides/file.json
|-- ./network
|   |-- ./network/file.json
|   `-- ./network/guides
|       `-- ./network/guides/file.json
`-- ./script.sh

6 directories, 8 files

When running the script, it should delete file.json file from every directory excluding the one with a "guides" name.

So the output should give:

|-- ./a
|   `-- ./a/b
|-- ./file.json
|-- ./folder
|-- ./guides
|   `-- ./guides/file.json
|-- ./network
|   `-- ./network/guides
|       `-- ./network/guides/file.json
`-- ./script.sh

6 directories, 4 files

My attempt to write code:

for directory in $(find . -maxdepth 40 -type d)
do
    if [[ ${directory##*/} != "guides" && ${directory##*/} != "." ]]
    then
        find ${directory##*/} -name "*file.json" -type f -delete
    fi
done

INCORRECT output of my code:

|-- ./a
|   `-- ./a/b
|-- ./file.json
|-- ./folder
|-- ./guides
|   `-- ./guides/file.json
|-- ./network
|   `-- ./network/guides
`-- ./script.sh

6 directories, 3 files

However this code does not work as expected.

What's the fix?

EDIT:

./guides/network/file.json file.json in this path should also be deleted.

CodePudding user response:

find . -type f -name file.json -not -path '*/guides/file.json' -exec rm -f {}  
  • -path is POSIX find, but it was added after 2004
  • * in a -path argument can match slashes
  • rm -v (logging) may be useful if your rm supports it

CodePudding user response:

Try

find . -type d -name guides -prune -o -type f -name file.json -exec rm -- {}  

See Delete all files except in a certain subdirectory with find for an explanation of why -exec rm ... has to be used instead of -delete.

  • Related