views:

207

answers:

4

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
This one would also remove a~b etc
njsf
+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
+5  A: 

Watch out for filenames with spaces in them!

find ./ -name "*~" -type f -print0 | xargs -0 rm
alberge
You should also probably add "-type f" to the find command so it only lists files, not directories.
alberge
How right you are. I never use filenames with space, and am out of practive protecting myself against them...
dmckee
Me neither, but sometimes they slip in unnoticed. Those devious spaces!
alberge
`-type f` Yeah. That's best, but rm -f will silently skip them anyway.
dmckee
What does -print0 | xargs -0 mean?and where should the type -f go?
Kys
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
+7  A: 

with GNU find

find /path -type f -name "*~" -exec rm {} +

or

find /path -type f -name "*~" -delete
ghostdog74
+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