What command can I use in linux to check if there is a file in a given directory (or its subdirectories) that contain a ~ at the end of the file's name? (Example if I am at a directory called t which contains many subdirectories, etc, I would like to remove any file that ends with a ~)
A:
you can use a find, grep, rm combination, something like
find | grep "~" | xargs rm -f
Probably others have better ideas :)
Alphaneo
2009-08-06 02:05:13
This one would also remove a~b etc
njsf
2009-08-06 02:17:46
+1
A:
find ./ -name '*~' -print0 | xargs -0 rm -f
Here find
will search the directory ./
and all sub directories, filtering for filenames that match the glob '*~' and printing them (with proper quoting courtesy of alberge). The results are passed to xargs
to be appended to rm -f
and the resulting string run in a shell. You can use multiple paths, and there are many other filters available (just read man find
).
dmckee
2009-08-06 02:06:02
+5
A:
Watch out for filenames with spaces in them!
find ./ -name "*~" -type f -print0 | xargs -0 rm
alberge
2009-08-06 02:07:03
You should also probably add "-type f" to the find command so it only lists files, not directories.
alberge
2009-08-06 02:09:16
How right you are. I never use filenames with space, and am out of practive protecting myself against them...
dmckee
2009-08-06 02:09:40
print0 and the -0 for xargs, use a NULL to terminate each filename in the stream. Without those two things, a file "a b c.txt" is treated as three files "a", "b" and "c.txt". And I put the -type f in, and upvoted since it's now a better answer :-)
paxdiablo
2009-08-06 02:27:09
+7
A:
with GNU find
find /path -type f -name "*~" -exec rm {} +
or
find /path -type f -name "*~" -delete
ghostdog74
2009-08-06 02:17:16
+1, both of these solutions avoid forking off a new process for each file to be removed; the second is slightly better, since it will never run into the problem of command line length limits if you're removing a very large number of files.
Adam Rosenfield
2009-08-06 02:20:55