6

I have to find files by size. Sizes are parameters. Result of found files must be saved to file. I already got this:

touch result.txt 
find /var/log -type f -size $1 -size $2 -exec ls {} \; > result.txt 

script shows me some results but I'm not sure they are right and nothing is saving to file.
Anybody can help?

3
  • 1
    Saving to file doesn't work with -exec. Use -ls instead. Also, a redirection will create a file if it doesn't exist yet, so the touch command is unnecessary.
    – Jos
    Nov 2, 2017 at 10:06
  • The size parameter has a couple of quirks that are described in man find. E.g. sizes are rounded up to the next unit (bytes, blocks, kb, Mb). Therefore, finding -1M would match only empty files. You would only use two parameters if you wanted to find files "less than $1" and "more than $2". Is that what you want?
    – Jos
    Nov 2, 2017 at 10:13
  • I want to find files which size i between these two parameters
    – J.Smith
    Nov 2, 2017 at 10:16

2 Answers 2

10

use like :

find /var/log -type f -size -10M -size +1M -exec ls {} \; > result.txt

It will store files name that have size more than 1Mb and less than 10Mb.

cat result.txt
/var/log/wtmp
/var/log/audit/audit.log.1
/var/log/audit/audit.log
/var/log/anaconda/journal.log
/var/log/mongo/mongod-11.0.0.11.log

If you pass as input parameters then use like:

find /var/log -type f -size -"$1"M -size +"$2"M -exec ls {} \; > result.txt

Below are the available units for size.

  -size n[cwbkMG]
          File uses n units of space, rounding up.  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 two-byte words

          `k'    for Kibibytes (KiB, units of 1024 bytes)

          `M'    for Mebibytes (MiB, units of 1024 * 1024 = 1048576
                 bytes)

          `G'    for Gibibytes (GiB, units of 1024 * 1024 * 1024 =
                 1073741824 bytes)
2
  • find has an ls option, that should be much faster.
    – dessert
    Nov 2, 2017 at 10:23
  • a simple tweak to look for any sizes: findsize () { rem="param1: dir, param2:min, param3:max" ; find "$1" -type f -size -"$3" -size +"$2" -exec ls '{}' ';' > result.txt ;} and use like: findsize /var/log 1M 10M to find the same as your exemple. Nov 2, 2017 at 14:04
2

The files you find can be sorted numerically (using the size column) like this

find /var/log -ls |sort -nk7

You can store the result in a file if you wish

find /var/log -ls |sort -nk7 > result.txt

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.