【问题标题】:Lowercase and replace spaces with dashes in MakeFile command for generating blog post filenameMakeFile 命令中的小写并用破折号替换空格以生成博客文章文件名
【发布时间】:2021-11-04 22:41:34
【问题描述】:

我想从命令行格式化字符串: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

【问题讨论】:

    标签: bash makefile hugo


    【解决方案1】:

    您的替换可能不足以将任何字符串清理为有效的文件名。但是使用您自己的规范(空格到小写,大写到小写):

    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 命令链接以及\ 行继续。它们都是必需的。

    【讨论】:

    • 似乎没有删除尾随的-。示例:make post title="Test" 创建文件 test-.md
    • 我无法在此处重现此内容。 make post title="Test" 创建 posts/test.md。无论如何,考虑到sed 命令s/-\+$//(在make 配方中s/-\+$$//),我看不出后面怎么会有-
    【解决方案2】:

    字符替换可以直接使用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
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-09
        • 1970-01-01
        • 2019-09-11
        • 2017-05-22
        • 2013-07-08
        • 1970-01-01
        • 1970-01-01
        • 2014-11-30
        相关资源
        最近更新 更多