1

I have thousands of txt files in one folder. Many of them are unnecessary for me. I want to delete all unnecessary files at once. If I do this manually (by opening every file, see it's content and delete it) it will require a lot of time and efforts. But I have some patterns (some words) (words are the content of the file, not the name of the file) that unnecessary files have. My required files do not have these patterns. So unnecessary files can be filtered and deleted using these patterns.

I have attached one screenshot of unnecessary file for better understanding. Highlighted word can be used as pattern. this

  • Please don't post screenshots of text. Copy the text here and use code formatting. – muru Aug 19 '18 at 1:11
2

You can use the commands grep and xargs in the following way:

grep -rlZ '=head1 NAME' /target-directory/ | xargs -0 rm -f

The grep command will work recursively -r (within the /target-directory/) and will output only the names of the files -l that contain the pattern '=head1 NAME'. The -Z option will output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name.

This output will be piped | to the stdin of the xargs command where -0 means that the input items will be terminated by a null character instead of by whitespace. The command that will be executed is rm -f that means force remove.

Thanks to @steeldriver for the final improvement of the answer!


In addition you can add -L1 (read one line per execution) to the xargs command and echo to perform dry run:

grep -rlZ '=head1 NAME' /target-directory/ | xargs -L1 -0 echo rm -f

If you want to move the files somewhere instead of delete them, modify the command in this way:

grep -rlZ '=head1 NAME' /tgt-dir/ | xargs -L1 -0 -I {} echo mv {} /destination-dir/

Or as @PerlDuck said "mv also has a switch -t, --target-directory=DIRECTORY which allows to put the directory first and the files last... This way mv isn't called once for each single file but once for a bunch of files.":

grep -rlZ '=head1 NAME' /tgt-dir/ | xargs -0 echo mv -t /destination-dir/
  • 1
    mv also has a switch -t, --target-directory=DIRECTORY which allows to put the directory first and the files last. With that you could speed up the xargs/mv combination: … xargs -0 echo mv -t /destination-dir/. This way mv isn't called once for each single file but once for a bunch of files. – PerlDuck Aug 18 '18 at 14:03
  • Thanks for the advice, @PerlDuck. I really do like the way how SE and especially Ask Ubuntu works :) – pa4080 Aug 18 '18 at 14:36
  • :-D You're welcome. Same for me. And hey, I already upvoted your answer the time you posted it. – PerlDuck Aug 18 '18 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy