Linux: A single commandline to delete files of a certain name from all subdirectories - How I Did It

in General Technical Discussion (PUBLIC)
Have you ever wanted to delete all files of a certain name from all subdirectories? For example, to delete large SQL Dumps named *.sql (after you used Tar to archive them and save space)?

Well, here is a quick one-liner to accomplish exactly that:

CAUTION: Of course, this example will PERMANENTLY DELETE files from your filesystem. Test before using this on anything important. We are not responsible for your mistakes.

To delete all .sql files in directories and subdirectories of user "john" (/home/john), do this:

  • sudo find /home/john -type f -name "*.sql" | xargs --replace=+ rm +

What it does:
  • "find" command provides a nice listing of filenames with their complete path. In this example, we are listing all files ending in ".sql" in in all subdirectories of "/home/john". Believe it or not, I don't think this is possible with the "ls" command (or we would have used it)!
  • "|" pipes the output to the next command
  • The "xargs" command "builds and executes command lines form standard input." In this example, we tell it to "rm" whatever files it is fed by the output of our find command (and remember those files include their complete paths). (You could tell it do all sorts of things with the files as well).
That's it! No script, no coding.

For more information you can read up on these commands by typing the following at your Linux command prompt:
man find
man xargs

Your rating: None Average: 5 (1 vote)

Post new comment

 

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.

Copyright © 2007-2013, WidWad LLC. All Rights Reserved.
All trademarks and service marks are the property of their respective owners.