How to move all files with fewer than 5 bytes in BASH?
Find!
You can use find to do this for you:
find . -type f -maxdepth 1 -size -5c -exec mv {} temp/ \;
Explanation
-size -5c
grabs all the files less than 5 bytes. The -
indicates less than and the c
indicates bytes.
-maxdepth 1
prevents you from trying to move the files on top of themselves when it tries to recurse into temp/ (after moving your initial files).
-exec mv {} temp/ \;
simply runs mv
on each file to put them in temp (the {} is substituted for the name of the file). The escaped semicolon marks the end of the mv command for exec.
There are other sizes available as well:
`b' for 512-byte blocks (this is the default if no suffix is used)`c' for bytes`w' for two-byte words`k' for Kilobytes (units of 1024 bytes)`M' for Megabytes (units of 1048576 bytes)`G' for Gigabytes (units of 1073741824 bytes)
find -size 1c
will give you all files that are exactly one byte.
As @user1666959 mentions, you can also use find . -type f -size -4c
, which will find all files in the current directory (and subdirectories), that are 4 bytes and smaller.
$ find . -maxdepth 1 -type f -size -4c -exec mv {} temp/ \;
(Yes, you will need the trailing \;
.
Note that find -size
allows for other exact file size matches (such as 1k
), but also allows you to search for files that take up the designated number of blocks on the disk (leaving off the unit).
$ man find
Provides a heap more info about how to use it to search.