Comments on Recursively remove files with the same name as the ones that end in `.part`
Parent
Recursively remove files with the same name as the ones that end in `.part`
I want to remove all files with the ".part" extension in the current directory and its subdirectories, including files with the same name but different extension.
Is this correct?
find . -name '*.part' -exec sh -c 'base="$(basename "$1" .part)"; find . -name "$base*" -delete' sh {} \;
Post
I might be inclined to try...
find . -type f -name '*.part' -exec sh -c '
[ -f "${1%.part}" ] && rm -i -- "${1%.part}";
for f in "${1%.part}".*; do
[ -f "$f" ] && rm -i -- "$f";
done
' -- {} \;
(newlines for readability; can be elided if one-liner means something to you...)
-
find . -type f -name '*.part'
— find files ending with .part -
-exec sh -c '...' -- {} \;
— run a shell script ... for each found file; path to file is in $1 in child script -
"${1%.part}"
— strip .part from the end of the filename in $1 (same asbasename
but without the extra process) -
[ -f "${1%.part}" ] && ...;
— if a file exists with no extension, do the ... bit -
rm -i -- "${1%.part}"
— delete the file with no extension -
for f in "${1%.part}".*; do ... done
— loop each found path matching the filename with any extension; path is stored in $f (this includes the one with the .part extension) -
[ -f "$f" ] && ...;
— if the path in $f exists and is a file, do the ... bit -
rm -i -- "$f"
— remove the file in $f
Note that I'm using various checks that the thing I'm asking to delete is a file, not a directory, link, fifo, etc.
If limiting only to files is less of a concern, you might well be able to shorten this to...
find . -name '*.part' -exec sh -c 'rm -i -- "${1%.part}" "${1%.part}".*' -- {} \;
The shell may write errors if the args to rm
don't expand to existing paths, hide that with judicious use of 2>/dev/null
redirection, if you care.
For fewer subshells, you may be able to pass all found files to the same shell in one go, with...
find . -name '*.part' -exec sh -c 'while [ -n "$1" ]; do rm -i -- "${1%.part}" "${1%.part}".*; shift; done' -- {} \+
...but this might be painful for larger file lists.
In general, note there's is technically a race condition between the various tests and the eventual delete, but that's only a concern if multiple processes are acting on that directory tree. Not sure how to avoid that.
Finally, rm -i
is used to prompt y/n
for each file to delete, as a safety net. Remove the -i
switch from the rm
calls if you are confident.
0 comment threads