You're looking to display file sizes specifically in MB, which is a great use case for understanding storage!
While ls -h automatically picks the best human-readable unit (K, M, G, etc.), if you only want to see sizes in Megabytes (MB), the standard ls command doesn't have a direct option to force only megabyte units.
However, you can achieve this by combining ls with another powerful command called awk for some simple text processing.
Here's how you can do it:
ls -l | awk '{print $9 ": " sprintf("%.2f", $5/1024/1024) "MB"}'
Let's break down this command:
ls -l: This lists the directory contents in a long format. The fifth field ($5) in this output is the file size in bytes.|: This is a pipe. It takes the output ofls -land feeds it as input to theawkcommand.awk '{print $9 ": " sprintf("%.2f", $5/1024/1024) "MB"}':awkis a powerful text processing tool.print ...: This tellsawkwhat to output.$9: This refers to the ninth field in thels -loutput, which is typically the filename.": ": Adds a colon and a space for readability.sprintf("%.2f", $5/1024/1024): This is the core calculation.$5: The file size in bytes from thels -loutput./1024/1024: Divides the byte size first by 1024 (to get kilobytes) and then again by 1024 (to get megabytes).sprintf("%.2f", ...): This formats the result as a floating-point number with exactly two decimal places.
"MB": Appends the "MB" string to the formatted number.
Example Usage and Output:
Let's say you have a file mybigfile.txt that is 5,242,880 bytes (exactly 5MB) and another file mysmallfile.txt that is 1,024,000 bytes (exactly 1MB).
If you run:
ls -l mybigfile.txt mysmallfile.txt | awk '{print $9 ": " sprintf("%.2f", $5/1024/1024) "MB"}'
You might see output like:
mybigfile.txt: 5.00MB
mysmallfile.txt: 1.00MB
This will give you the file sizes precisely in MB with two decimal places.
Keep in mind that awk ignores the header line of ls -l (the line with "total N"), so it won't try to parse that.
Feel free to try it out on your system! This is a great way to customize command output for specific needs.