LINUX下的 du 命令是用来查看文件大小的(指定文件 或者文件夹下的所有文件). 和touch命令一样 接下来我们会只用 windows 内置的批处理来进行简单的功能实现. 主要是实现 -h 和 -c 开关. -h 参数是用来显示成多少K, 多少M比较可读的大小. 而 -c 则会在最后显示一共的大小. 比如以下例子(假设当前目录下只有一个 sample.txt 文件)
# du
1024 sample.txt
# du -h
1K sample.txt
# du -hc
1K sample.txt
1K total
在批处理里 你可以通过%~z1 来显示文件的大小 例如:
@echo off
echo %~z1
如果在批处理里 需要获得指定文件的大小 可以通过 for 来实现:
for %%i in (file.txt) do (echo %%~zi)
-c 开关则需要一个变量来累计:
set /a total=!total!+%%~zi
当然在 批处理的开头你需要指定:
setlocal enabledelayedexpansion
来允许变量延时更新.
可以通过 标签来声明一个子函数用于显示 文件大小多少K 或者多少M.
:H
:: -h 开关 %1 是文件大小(字节) %2 是显示的文件或者字符串
setlocal enabledelayedexpansion
set /a totalK=%1/1024
set /a totalM=%1/1024/1024
set /a totalG=%1/1024/1024/1024
if !totalG! gtr 0 (
echo !totalG!G %sep% %2
) else (
if !totalM! gtr 0 (
echo !totalM!M %sep% %2
) else (
if !totalK! gtr 0 (
echo !totalK!K %sep% %2
) else (
echo %1 %sep% %2
)
)
)
endlocal
完整的代码(以下)在 github:
@echo off
:: WINDOWS 批处理简单实现 du 文件大小命令
:: 支持 -h -c 开关
:: https://helloacm.com
setlocal enabledelayedexpansion
set switch_c=False
set switch_h=False
set anyfiles=False
set /a total=0
set /a totalK=0
set /a totalG=0
set /a totalM=0
set sep=%TAB% %TAB% %TAB% %TAB% %TAB% %TAB%
:start
if %1.==. goto :end
if "%1"=="-c" (
set switch_c=True
shift
goto :start
)
if "%1"=="-h" (
set switch_h=True
shift
goto :start
)
if "%1"=="-ch" (
set switch_h=True
set switch_c=True
shift
goto :start
)
if "%1"=="-hc" (
set switch_h=True
set switch_c=True
shift
goto :start
)
set anyfiles=True
if not exist "%1" (
echo %0: 无法访问 ‘%1': 没有这样的文件或者文件夹
shift
goto :start
)
:: check each given input files
for %%i in (%1) do (
set /a total=!total!+%%~zi
if %switch_h%==True (
call :H %%~zi %%i
) else (
echo %%~zi %sep% %%i
)
)
shift
goto :start
:end
:: 如果没有指定文件 则默认显示当前目录下的所有文件
if %anyfiles%==False (
for /f %%i in ('dir * /b') do (
set /a total=!total!+%%~zi
if %switch_h%==True (
call :H %%~zi %%i
) else (
echo %%~zi %sep% %%i
)
)
)
:: 一共大小 (-h 开关 单位K, M, G)
if %switch_c%%switch_h%==TrueTrue (
call :H !total! total
)
:: 一共大小 (字节)
if %switch_c%%switch_h%==TrueFalse (
echo !total! %sep% total
)
goto :eof
:H
:: 显示单位 K, M, G 的子函数
setlocal enabledelayedexpansion
set /a totalK=%1/1024
set /a totalM=%1/1024/1024
set /a totalG=%1/1024/1024/1024
if !totalG! gtr 0 (
echo !totalG!G %sep% %2
) else (
if !totalM! gtr 0 (
echo !totalM!M %sep% %2
) else (
if !totalK! gtr 0 (
echo !totalK!K %sep% %2
) else (
echo %1 %sep% %2
)
)
)
endlocal
goto :eof
endlocal
英文: A Simple du Implementation using Windows Batch Programming
本文一共 346 个汉字, 你数一下对不对.上一篇: 一张图告诉你北京的雾霾有多严重
下一篇: 找到一个存放转载各种文章的地方
扫描二维码,分享本文到微信朋友圈
