1

In my main_dir, I have a lot of sub-folders say DFT1 to DFT150, and in each directory, there is a file named OSZICAR. However, some of this would have file size 0.

So I would like to have a script, that goes into each folder and checks the size of OSZICAR, if it is below size of 10 bytes, then delete its DFT folder.

The pseudo-code (which doesn't work), I have is:

for f in *; do
 cd $f
 status=(check whether OZICAR has size below 10bytes)
 cd ..
 if (status); do
  rm -r $f
 fi 
done
  • With bash: if [ ! -s file ] ; then. Citing man bash: " -s file True if file exists and has a size greater than zero." I.e. -s = look for non-empty files. – Fiximan Sep 1 '15 at 11:44
3

Use find:

find DFT*/OSZICAR -size -10c -printf "%h\0" | xargs -r0 rm -r
  • find searches for all files inside a DFT* directory called OSZICAR, whose file size is below 10 bytes; the c means bytes.
  • Then find prints the directory name %h where the file was found (DFT105 for instance), terminated by a nullbyte \0
  • This is piped to xargs which reads the line terminated by a nullbyte -0 and calls rm -r on every of them.

I recommend to call the command without the xargs part, to check if everything works correctly, before deleting anything.

Edit: If your find doesn't accept the -printf (like OSX) option, use this instead:

find DFT*/OSZICAR -size -10c -exec sh -c 'rm -r $(dirname "$1")' sh {} \;
| improve this answer | |
  • I just try: but it gives me error : dhcp-18-189-47-44:CE-06-new-stuctures_backup wenxuanhuang$ find DFT*/OSZICAR -size -10c -printf "%h\0" find: -printf: unknown primary or operator – user40780 Sep 1 '15 at 7:35
  • I am using Mac OS 10.9, but does this affect? Thank you. – user40780 Sep 1 '15 at 7:45
  • @user40780 See my edit – chaos Sep 1 '15 at 7:51
  • Thank you, do you know where could I know about what does $(dirname "$1") mean? Thank you. – user40780 Sep 1 '15 at 8:09
  • @user40780 find prints the paths of the files with a filesize below 10 bytes, dirname removes the filename part from the path, hence prints only the name of the directory containing the file (the one you want to delete), see man dirname – chaos Sep 1 '15 at 8:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.