Shell脚本递归转换.md文件为.html文件的文件名问题求助
Fixing the .md.html Filename Issue When Converting Markdown Files
I feel you—those double suffixes are such a frustrating gotcha when working with find and -exec! The problem is that {} inserts the full filename (including the .md extension), so appending .html just tacks it right onto the end. Here's how to fix it properly:
The Corrected Command
find . -name '*.md' -exec sh -c ' for file do markdown-html "$file" -s resources/styles/common-custom.css -o "${file%.md}.html" done ' sh {} +
Why This Works
Let’s break down the key bits that solve the filename problem:
sh -c '...' sh {} +: This runs a single shell instance to process all found files at once (way more efficient than using\;, which spins up a new shell for every file).${file%.md}: This is shell parameter expansion magic—it strips the shortest matching.mdsuffix from the filename. Sohome.mdbecomeshome, and adding.htmlgives you the cleanhome.htmlyou want.- The
for file doloop handles every file passed byfind, making sure each one gets converted correctly.
Alternative: Using -execdir (For Per-Directory Processing)
If your version of find supports -execdir (most modern ones do), this approach runs the command directly in the directory of each file—handy if your resources/styles path is relative to where the script runs:
find . -name '*.md' -execdir sh -c ' markdown-html "$1" -s resources/styles/common-custom.css -o "${1%.md}.html" ' sh {} \;
Either method will eliminate those messy .md.html filenames and give you the clean, correctly named HTML files you’re after!
内容的提问来源于stack exchange,提问作者RoHaN
相关产品推荐
相关产品推荐

