Extract text from DOCX files using shell commands when python-docx is unavailable
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-docx-shell-parse-d7ec11bef00b ,按照其中的说明把「docx-shell-parse」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
When you need to read content from Microsoft Word (.docx) files but python-docx or similar libraries are unavailable, use this shell-based approach to extract text reliably.
python-docx or similar librariesDOCX files are ZIP archives containing XML files. Extract and parse the main document XML:
unzip -p filename.docx word/document.xml | sed -e 's/<[^>]*>//g'
ls -la document.docx
Use unzip -p to pipe the document.xml content directly to stdout:
unzip -p document.docx word/document.xml
Pipe through sed to remove all XML tags:
unzip -p document.docx word/document.xml | sed -e 's/<[^>]*>//g'
For cleaner output, remove excessive whitespace and newlines:
unzip -p document.docx word/document.xml | \
sed -e 's/<[^>]*>//g' | \
sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | \
sed -e '/^$/d'
unzip -p document.docx word/document.xml | \
sed -e 's/<[^>]*>//g' > output.txt
Add this reusable function to your scripts:
parse_docx() {
local file="$1"
if [ ! -f "$file" ]; then
echo "Error: File not found: $file" >&2
return 1
fi
unzip -p "$file" word/document.xml 2>/dev/null | \
sed -e 's/<[^>]*>//g' | \
sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | \
sed -e '/^$/d'
}
# Usage: parse_docx document.docx
Confirm extraction worked by checking output:
parse_docx document.docx | head -20
For more complex parsing needs:
tmpdir=$(mktemp -d)
unzip document.docx -d "$tmpdir"
cat "$tmpdir/word/document.xml" | sed -e 's/<[^>]*>//g'
rm -rf "$tmpdir"