I need to delete everything in directory d1
, except the file d1/d2/f1.txt
. How can I do that in bash?
CodePudding user response:
This works. It will delete everything, but the directories in path of f1.txt
and of course the file itself.
find d1/ ! -iregex '\(d1/\|d1/d2\|d1/d2/f1.txt\)' -delete
However, I would strongly suggest against using -delete
as it is permanent and mistyping a character could be disastorous...
You should try something like this instead, putting files and directories in trash folder first just in case you delete a file you don't want to delete you can recover it.
mkdir -p ~/.Trash
find d1/ ! -iregex '\(d1/\|d1/d2\|d1/d2/f1.txt\)' -exec mv {} ~/.Trash \;
CodePudding user response:
Find the contents to delete except for (!
) specific file:
find d1/ -type f ! -name 'd1/d2/f1.txt' -delete
CodePudding user response:
find d1 -depth ! -path d1/d2/f1.txt -exec echo rm -d {}
Remove echo
if the output looks right.