文章目录
gitbash__git_1">git,bash - 从一个远端git库只下载一个文件的方法
概述
github上有很多大佬上传了电子书库,如果只相中一本书,也要去迁出整个库,急死个人。
试了 Git稀疏检出 的方法,不现实,因为对于一个巨大的库,那也下载好久啊(git库的元数据就很大)。
只能是用git库页面的下载raw文件的方法,只是说,是用工具来下载,还是手工点击用浏览器来下载的区别。
笔记
有的库,是卖书的人上传的,将书对应的pdf都删了,所以也没法下载raw文件。
所以只要浏览到库中的书,确实存在,就可以用下载raw文件。
如果想用bash脚本来下载,只是收集url, 可以F12来找raw file url.
开始没明白,直接下载网页上的url, 实际下载的是html.
下载后,发现.pdf尺寸不对,才200K+,打开一看,原来是这个页面的html.
在html中找raw file url
"rawBlobUrl":"https://github.com/weaiken/ebook/raw/refs/heads/master/03_operating_system/UNIX%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E8%AE%BE%E8%AE%A1.pdf
在git bash窗口中,按照自己找到的实际raw file url来下载就Ok了。
curl -L -o UNIX操作系统设计1.pdf https://github.com/weaiken/ebook/raw/refs/heads/master/03_operating_system/UNIX%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E8%AE%BE%E8%AE%A1.pdf
写一个bash脚本来自动下载
github_raw_file_from_urlsh_27">get_github_raw_file_from_url.sh
#!/bin/bash
# @file get_github_raw_file_from_url.sh
# @brief 从url中提取文件名(包括后缀)
# e.g. get_github_raw_file_from_url.sh https://github.com/weaiken/ebook/blob/master/03_operating_system/UNIX%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E8%AE%BE%E8%AE%A1.pdf
clear
# 参数检查
if [ $# -ne 1 ]; then
echo "错误:需要且只能输入一个URL参数" >&2
exit 1
fi
# 提取URL中的文件名部分
encoded_file=$(basename "$1") # 或使用:encoded_file=${1##*/}
# URL解码函数
urldecode() {
local encoded=$1
printf '%b' "${encoded//%/\\x}" 2>/dev/null | sed 's/+/ /g'
}
# 执行解码并输出结果
decoded_file=$(urldecode "$encoded_file")
echo "原始文件为: $encoded_file"
echo "提取的中文文件名:$decoded_file"
curl -L -o $decoded_file $1
./rename_file.sh $decoded_file $decoded_file html
html_file="$decoded_file.html"
echo "html file = $html_file"
raw_url=$(./find_key_value.sh $html_file "rawBlobUrl")
echo "raw_url = $raw_url"
curl -L -o $decoded_file $raw_url
echo "file download over : $decoded_file"
reanme_file.sh
#!/bin/bash
# @file reanme_file.sh
# @brief 将参数1的文件名 改名为 参数2.参数3
# e.g. rename_file.sh a.pdf a.pdf html
# a.pdf => a.pdf.html
set -euo pipefail
# 参数校验
if [ $# -ne 3 ]; then
echo "错误:需要3个参数,用法:$0 原文件名 前缀 后缀" >&2
exit 1
fi
original_file="$1"
new_name="$2.$3"
# 文件存在性检查
if [ ! -f "$original_file" ]; then
echo "错误:文件 '$original_file' 不存在" >&2
exit 1
fi
# 执行重命名
mv -v "$original_file" "$new_name"
echo "重命名成功:$original_file -> $new_name"
find_key_value.sh
#!/bin/bash
# find_key_value.sh
# 用法:./a.sh <html文件> <键名>
html_file=$1
key_name=$2
# 使用正则表达式匹配JSON格式的键值对
value=$(grep -oP "\"$key_name\"\s*:\s*\"\K[^\"]+" "$html_file" | head -1)
# 验证结果并输出
if [ -z "$value" ]; then
echo "未找到 $key_name 对应的值" >&2
exit 1
else
echo "$value"
exit 0
fi
执行命令
git库文件的html url, 可以从浏览器url标题栏拷贝
https://www.github.com/weaiken/ebook/blob/master/03_operating_system/UNIX操作系统设计.pdf
在git bash命令行窗口中执行命令
脚本写的粗糙,必须保证网络正常。
./get_github_raw_file_from_url.sh https://github.com/weaiken/ebook/blob/master/03_operating_system/UNIX%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E8%AE%BE%E8%AE%A1.pdf
这个工具脚本已经实现了从库文件浏览到的实际html用户页面下载实际的库文件对应的raw原始文件。