You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Makefile中借助tr命令格式化生成小写横杠分隔的Hugo博文文件名

解决方案

你可以通过Make的shell函数调用tr命令实现格式化,修改后的完整Makefile如下:

# 传入参数校验,避免无title时执行异常
ifeq ($(title),)
$(error 未检测到title参数,请按以下格式执行: make post title='你的文章标题')
endif

# 格式化title为文件名格式:空格替换为横杠、全小写
shouldBeFormattedTitle := $(shell echo '$(title)' | tr ' ' '-' | tr '[:upper:]' '[:lower:]')

post:
	@echo "New post: $(title)"
	hugo new posts/"$(shouldBeFormattedTitle)".md

注意事项

  • Makefile中post规则下的所有行开头必须使用Tab字符缩进,不能使用空格,否则会触发missing separator类报错
  • 如果你的文章标题可能包含单引号,可以将shell调用部分修改为$(shell echo "$(title)" | tr ' ' '-' | tr '[:upper:]' '[:lower:]')避免截断

如果你使用的是GNU Make 3.80及以上版本,还可以使用内置字符串处理函数实现相同效果,不需要依赖外部tr命令,跨平台兼容性更好:

ifeq ($(title),)
$(error 未检测到title参数,请按以下格式执行: make post title='你的文章标题')
endif

# 定义空格变量用于替换逻辑
null :=
space := $(null) #

# 内置函数实现:先转全小写、再把空格替换为横杠
shouldBeFormattedTitle := $(subst $(space),-, $(lower $(title)))

post:
	@echo "New post: $(title)"
	hugo new posts/"$(shouldBeFormattedTitle)".md

内容的提问来源于stack exchange,提问作者lata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:45:05