Last active
September 5, 2024 08:05
-
-
Save gecko655/a3c6f0b9bcec210a8158a50584ed946c to your computer and use it in GitHub Desktop.
extract_excel_external_links.bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
main() { | |
target_file_glob="${1}" | |
tmpdir="${2}" | |
for target_file in $target_file_glob; do | |
# ファイル名に ~ を含んでいたらスキップ | |
if [[ $target_file == *~* ]]; then | |
continue | |
fi | |
workdir=${tmpdir}/$(basename "$target_file" .xlsx) | |
echo "===== ${target_file} =====" | |
# エクセルファイルを一時ディレクトリに解凍する | |
unzip "${target_file}" -d "${workdir}" 1>/dev/null 2>&1 | |
# sheet 内にある externalLinks を検索 | |
found_external_links=$(for file in "${workdir}"/xl/worksheets/*.xml; do | |
# sheet 内の関数表現 <f></f> を抽出し、[] で囲まれた数字を取り出す | |
yq -p xml -oy '.. | select(key == "f")' "$file" | grep -E -o '\[[0-9]*\]' | sed 's/[][]//g' | |
done | sort | uniq) | |
# 見つかった externalLink のリンク先を表示 | |
for link in ${found_external_links}; do | |
echo -n "[$link]:" | |
# memo: ([] + elem)[] は、 elem が array でも single object でも対応できるようにするおまじない | |
# memo: file not found も出力に出したいので、標準エラー出力を標準出力にリダイレクトする | |
(cat "${workdir}/xl/externalLinks/_rels/externalLink${link}.xml.rels" | yq -p xml '([] + .Relationships.Relationship)[] | select(.+@Id == "rId1") | .+@Target') 2>&1 | |
done | |
done | |
} | |
# yq がインストールされていない場合はインストールを促す | |
if ! command -v yq 1>/dev/null 2>&1; then | |
echo "yq command not found. Please install yq command via \"brew install yq\"" 1>&2 | |
exit 1 | |
fi | |
# 引数の個数が1つでない場合はエラーを出力して終了 | |
if [[ $# -ne 1 ]]; then | |
echo "Usage: $0 <target_file_glob>" 1>&2 | |
exit 1 | |
fi | |
# zip展開用一時ディレクトリ作成 | |
_tmpdir=$(mktemp -d) | |
trap finally EXIT | |
finally() { | |
# 一時ディレクトリとファイルを削除 | |
rm -r ${_tmpdir} | |
} | |
main "${1}" ${_tmpdir} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment