在生成博客文章文件名的MakeFile命令中,小写并用破折号替换空格



我想格式化命令行中的字符串:make post title='This is a hello world post!'。标题字符串的格式应类似于:$(title) | tr ' ' '-' | tr '[:upper:]' '[:lower:]'

MakeFile创建了一个新的Hugo博客条目:

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

问题是,如何将上述tr命令(或替代命令(用于shouldBeFormattedTitle

您的替换可能不足以将任何字符串净化为有效的文件名。但根据您自己的规范(空格到字母,大写到小写(:

post:
@echo "New post: $(title)"
shouldBeFormattedTitle=$$(echo "$(title)" | tr ' ' '-' | 
tr '[:upper:]' '[:lower:]'); 
hugo new posts/"$$shouldBeFormattedTitle".md

演示:

make post title='This is a hello world post! Date: 2021/11/04'
New post: This is a hello world post! Date: 2021/11/04
hugo new posts/this-is-a-hello-world-post!-date:-2021/11/04.md

正如您所看到的,在文件名中,其他一些字符可能是一个真正的问题。如果你真的想清除字符串(并且它不包含换行符(,你可以尝试:

post:
@echo "New post: $(title)"
shouldBeFormattedTitle=$$(echo "$(title)" | tr '[:upper:]' '[:lower:]' | 
tr -c a-z0-9 - | sed 's/--+/-/g;s/^-+//;s/-+$$//'); 
hugo new posts/"$$shouldBeFormattedTitle".md

tr -c a-z0-9 --替换所有非字母数字字符,sed命令删除前导、尾随和重复的-。演示:

$ make post title='This is a hello world post! Date: 2021/11/04'
New post: This is a hello world post! Date: 2021-11-04
hugo new posts/this-is-a-hello-world-post-date-2021-11-04.md

如果使用其中一个或另一个,请注意$$、带有分号的shell命令的链接以及行的连续性。他们都是需要的。

字符替换可以使用Makefile函数直接完成,但大小写修改可能需要外部shell命令:

.PHONY: title
e :=
formatted = $(shell title="$(subst $(e) $(e),-,$(title))"; echo "$${title,,}")
title:
@echo "$(formatted)"

测试:

$ make title='S O M E T H I N G' title
s-o-m-e-t-h-i-n-g

我会使用shell函数(未验证(生成字符串:

title ?= no_title
new_post := posts/$(shell $(title) | tr ' ' '-' | tr '[:upper:]').md
post: $(new_post)
$(new_post):
@echo "New post: $(title)"
hugo new $@

最新更新