Home > other >  Lowercase and replace spaces with dashes in MakeFile command for generating blog post filename
Lowercase and replace spaces with dashes in MakeFile command for generating blog post filename

Time:11-05

I would like to format string from the command line: make post title='This is a hello world post!'. The title string should be formatted like: $(title) | tr ' ' '-' | tr '[:upper:]' '[:lower:]'.

The MakeFile create a new Hugo blog entry:

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

Question is, how can I use the above tr commands (or alternative) for shouldBeFormattedTitle?

CodePudding user response:

Your substitutions are probably not enough to sanitize any string into a valid file name. But with your own specifications (spaces to hiphens and uppercase to lowercase):

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

Demo:

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

As you can see, some other characters can be a real problem in a file name. If you really want to sanitize the string (and it does not contain newline characters), you could try:

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

The tr -c a-z0-9 - replaces all non-alpha-numeric characters by - and the sed command removes the leading, trailing and duplicate -. Demo:

$ 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

If you use one or the other pay attention to the $$, to the chaining of the shell commands with a semi-colon and to the \ line continuation. They are all needed.

CodePudding user response:

Character replacement can be done directly using a Makefile function, but case modifications may need an external shell command:

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

A test:

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

CodePudding user response:

I'd generate the string using a shell function (unverified):

title ?= no_title
new_post := posts/$(shell $(title) | tr ' ' '-' | tr '[:upper:]').md
post: $(new_post)

$(new_post):
    @echo "New post: $(title)"
    hugo new $@
  • Related