我想從命令列格式化字串:make post title='This is a hello world post!'. 標題字串的格式應為:$(title) | tr ' ' '-' | tr '[:upper:]' '[:lower:]'。
將MakeFile創建一個新的雨果博客條目:
post:
@echo "New post: $(title)"
hugo new posts/"$(shouldBeFormattedTitle)".md
問題是,我如何使用上述tr命令(或替代命令)shouldBeFormattedTitle?
uj5u.com熱心網友回復:
您的替換可能不足以將任何字串清理為有效的檔案名。但是根據您自己的規范(空格到 hihens 和大寫到小寫):
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 命令以及\行的延續。他們都是需要的。
uj5u.com熱心網友回復:
字符替換可以直接使用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
uj5u.com熱心網友回復:
我會使用 shell 函式(未經驗證)生成字串:
title ?= no_title
new_post := posts/$(shell $(title) | tr ' ' '-' | tr '[:upper:]').md
post: $(new_post)
$(new_post):
@echo "New post: $(title)"
hugo new $@
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350261.html
上一篇:引入分隔匹配部分的空行
