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
1
  • 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. Commented Sep 1, 2015 at 11:44

1 Answer 1

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 {} \;
5
  • 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 Commented Sep 1, 2015 at 7:35
  • I am using Mac OS 10.9, but does this affect? Thank you. Commented Sep 1, 2015 at 7:45
  • @user40780 See my edit Commented Sep 1, 2015 at 7:51
  • Thank you, do you know where could I know about what does $(dirname "$1") mean? Thank you. Commented Sep 1, 2015 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 Commented Sep 1, 2015 at 8:32

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.