سؤال

I have to write a unix script and I am really not familiar with it and need help.

I have a root directory, inside it I have a lot of other directories. Each directory contains txt files. I have to go through all the directories and all the files:

  • If a file contains the phrase "file information" I want to keep the file.

  • If the file does not contain it, I want to delete the file.

  • Then, If all the files of a directory have been deleted, and the
    directory is empty, I want to delete the directory.

How can I write a script like that?

Thanks

هل كانت مفيدة؟

المحلول

to delete all files that contains "STRING":

rm -rf $(find . -type f -exec grep -l 'STRING' {} \;)

and to delete all empry directories:

find . -empty -type d -delete

UPDATE

from man grep:

-L, --files-without-match

          Suppress normal output; instead print the name of each input file from which no output would normally  have  been  printed.
          The scanning will stop on the first match.

-l, --files-with-matches

          Suppress  normal output; instead print the name of each input file from which output would normally have been printed.  The
          scanning will stop on the first match.  (-l is specified by POSIX.)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top