Shell script to delete files smaller than x kb

I am trying to figure out how to write a small script to delete text files that are less than 50 kilobytes in size, but I have no success.

My attempt looks like this:

#!/bin/bash
for i in *.txt
do
   if [ stat -c %s < 5 ]
   then
     rm $i
   fi
done

      

I would suggest some recommendations, thanks!

+3


source to share


2 answers


You should be using fedorqui version, but for reference:

#!/bin/bash
for i in ./*.txt   # ./ avoids some edge cases when files start with dashes
do
  # $(..) can be used to get the output of a command
  # use -le, not <, for comparing numbers
  # 5 != 50k
  if [ "$(stat -c %s "$i")" -le 50000 ]
  then
    rm "$i"  # specify the file to delete      
  fi # end the if statement
done

      



It is usually easier to write a program piece by piece and verify that each piece works, rather than writing the entire program and then trying to debug it.

+3


source


You can directly use find

with an option size

for this:

find /your/path -name "*.txt" -size -50k -delete
                              ^^^^^^^^^^
                              if you wanted bigger than 50k, you'd say +50

      

You may want to stick with the files in the current directory without going down in the directory structure. If so, you can say:

find /your/path -maxdepth 1 -name "*.txt" -size -50k -delete

      




From man find

:

-size n [cwbkMG]

The file uses n units of space. The following suffixes can be used:

'b' for 512-byte blocks (this is the default if no suffix is ​​used)

'c' for bytes

'w' for double-byte words

'k' for Kilobytes (units of 1024 bytes)

'M' for megabytes (units 1048576 bytes)

'G' for gigabytes (units 1073741824 bytes)

+10


source







All Articles