简体   繁体   English

用于删除小于x kb的文件的Shell脚本

[英]Shell script to delete files smaller than x kb

I'm trying to find out how to write a little script to delete text files that are smaller than 50 Kilobytes but I have had no success. 我试图找出如何编写一个小脚本来删除小于50千字节的文本文件,但我没有成功。

My attempt looks like this: 我的尝试看起来像这样:

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

I would appriciate some guidance, thank you! 我会赞美一些指导,谢谢!

You can directly use find with the size option for this: 您可以直接使用带有size选项的find

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

You may want to stick to 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 : man find

-size n[cwbkMG] -size n [cwbkMG]

File uses n units of space. 文件使用n个空格单位。 The following suffixes can be used: 可以使用以下后缀:

'b' for 512-byte blocks (this is the default if no suffix is used) 'b'表示512字节块(如果没有使用后缀,这是默认值)

'c' for bytes 'c'表示字节

'w' for two-byte words 两个字节的单词'w'

'k' for Kilobytes (units of 1024 bytes) Kilobytes的'k'(1024字节单位)

'M' for Megabytes (units of 1048576 bytes) 'M'表示兆字节(单位为1048576字节)

'G' for Gigabytes (units of 1073741824 bytes) 千兆字节'G'(单位1073741824字节)

You should use fedorqui's version, but for reference: 您应该使用fedorqui的版本,但供参考:

#!/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's usually easier to write a program piece by piece and verifying that each part works, rather than writing the entire program and then trying to debug it. 通常更容易编写一个程序并验证每个部分是否正常工作,而不是编写整个程序然后尝试调试它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM