有没有办法获得像这样的远程文件的大小
http://api.twitter.com/1/statuses/public_timeline.json
Run Code Online (Sandbox Code Playgroud)
在shell脚本?
cod*_*ict 95
您可以下载该文件并获取其大小.但我们可以做得更好.
在响应头中查找Content-Length:将跟随文件大小的字节数.
$ URL="http://api.twitter.com/1/statuses/public_timeline.json"
$ curl -sI $URL | grep -i Content-Length
Content-Length: 134
Run Code Online (Sandbox Code Playgroud)
要获得大小,请使用过滤器从上面的输出中提取数字部分:
$ curl -sI $URL | grep -i Content-Length | awk '{print $2}'
134
Run Code Online (Sandbox Code Playgroud)
Jam*_*s H 22
其他答案有两点需要注意:
此外,您可以在没有grep/awk或管道的情况下执行此操作:
curl 'http://api.twitter.com/1/statuses/public_timeline.json' --silent --write-out 'size_download=%{size_download}\n' --output /dev/null
Run Code Online (Sandbox Code Playgroud)
和压缩相同的请求:
curl 'http://api.twitter.com/1/statuses/public_timeline.json' --silent -H 'Accept-Encoding: gzip,deflate' --write-out 'size_download=%{size_download}\n' --output /dev/null
Run Code Online (Sandbox Code Playgroud)
类似于codaddict的答案,但没有呼吁grep:
curl -sI http://api.twitter.com/1/statuses/public_timeline.json | awk '/Content-Length/ { print $2 }'
Run Code Online (Sandbox Code Playgroud)
当存在重定向时,前面的答案将不起作用.例如,如果想要debian iso DVD的大小,他必须使用--location选项,否则,报告的大小可能是302 Moved Temporarily答案体的大小,而不是真实文件的大小.
假设您有以下网址:
$ url=http://cdimage.debian.org/debian-cd/8.1.0/amd64/iso-dvd/debian-8.1.0-amd64-DVD-1.iso
Run Code Online (Sandbox Code Playgroud)
使用curl,您可以获得:
$ curl --head --location ${url}
HTTP/1.0 302 Moved Temporarily
...
Content-Type: text/html; charset=iso-8859-1
...
HTTP/1.0 200 OK
...
Content-Length: 3994091520
...
Content-Type: application/x-iso9660-image
...
Run Code Online (Sandbox Code Playgroud)
这就是我喜欢使用的原因HEAD,这是libwww-perl包(在debian上)lwp-request命令的别名.它的另一个优点是它剥离了额外的\ r \n字符,这简化了后续的字符串处理.
因此,要检索debian iso DVD的大小,可以做一个例子:
$ size=$(HEAD ${url})
$ size=${size##*Content-Length: }
$ size=${size%%[[:space:]]*}
Run Code Online (Sandbox Code Playgroud)
请注意:
对于其他炮弹,你可能不得不求助于sed,awk,grep等.
使用 cURL 以静默模式运行-s,
只拉标题-I(以避免下载整个文件)
然后做一个不区分大小写的grep -i
并使用 awk 返回第二个参数$2。
输出返回为 bytes
curl -sI http://api.twitter.com/1/statuses/public_timeline.json | grep -i content-length | awk '{print $2}'
//output: 52
Run Code Online (Sandbox Code Playgroud)
或者
curl -sI https://code.jquery.com/jquery-3.1.1.min.js | grep -i content-length | awk '{print $2}'
//output: 86709
Run Code Online (Sandbox Code Playgroud)
或者
curl -sI http://download.thinkbroadband.com/1GB.zip | grep -i content-length | awk '{print $2}'
//output: 1073741824
Run Code Online (Sandbox Code Playgroud)
如果您想以千字节为单位显示大小,请将 awk 更改为:
awk '{print $2/1024}'
Run Code Online (Sandbox Code Playgroud)
或兆字节
awk '{print $2/1024/1024}'
Run Code Online (Sandbox Code Playgroud)