Find size of file in MB

How to find the size of file in MB in UNIX command line?


Solution 1:

If your ls supports --block-size such as GNU coreutils ls does:

ls -s --block-size=1048576 filename | cut -d' ' -f1

Solution 2:

du -h file

OR

ls -lh file

EDIT

this answer is wrong since it can report size also in Gb/Kb, depending on the file's size. Please remove upvotes.

Solution 3:

I tend to use 'du -k myfile' to get kbytes and visually drop the last three digits, but I'm just looking for approximate size.

Turns out that du often (always?) has -m option for MB.

Keep in mind that how large the file likely differs slightly from the amount of diskspace used, as the disk allocation occurs in blocks, not bytes.

If you are looking for 'fat' files because of low diskspace, that would be a more enlightening question, as the solutions would be more varied.

Solution 4:

using -lh option will give you sizes in human readable form, e.g if your file is of size 1025 M it will output 1G, otherwise you can use ls --block-size=1024K -s it will give size in nearest integer in MBs.
If you need precise values (not rounded ones) you can go for awk:

ls -l | awk '/d|-/{printf("%.3f %s\n",$5/(1024*1024),$9)}'

Solution 5:

stat can do this.

$ ls -l | grep myfile
-rw-------  1 rory rory      3120 2009-07-02 16:58 myfile
$ stat -c '%s' myfile
3120

that give it to you in bytes.

You can use bash's arithmetic to calculate the megabytes:

$ echo $(( $( stat -c '%s' myfile ) / 1024 / 1024 ))
0

(but it rounds it down in this case)