我有一个变量,WORKSPACE
它是/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en
我想从每一行中删除它并创建两个变量。
例如,从线上看,
"/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en/references/architecture/recipes/hermit.md",
要得到
category=references/architecture/recipes
title=hermit.md
该线具有不同的深度:
"/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en/guides/faq.md",
要得到
category=guides
title=faq.md
ETC。
我尝试了以下方法,但它只得到最后两项。
title=$(basename "$line")
filedirname=$(dirname "$line")
category=$(basename $filedirname)
我怎样才能用 Bash 做到这一点?
答案1
我假设类别和标题由/.vivliostyle/tauri/en
路径名后面的内容确定。
具有以下条件
WORKSPACE="/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en"
您可以使用以下方法bash
来获得所需的结果:
pathname="${line#$WORKSPACE/}"
#or
pathname="${line/$WORKSPACE\/}" #replaces $WORKSPACE/ with nothing
#Getting category:
category="${pathname%/*}"
echo "Category: $category"
#Getting title:
title="${pathname##*/}"
echo "Title: $title"
所以有这条路:
line="/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en/references/architecture/recipes/hermit.md"
使用上面的代码你将得到:
Category: references/architecture/recipes
Title: hermit.md
并有这条路径:
line="/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en/guides/faq.md"
你得到:
Category: guides
Title: faq.md
解释
pathname="${line#$WORKSPACE/}"
与上面的行我正在删除$WORKSPACE/
变量包含什么$line
。
因此,该字符串/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en/
将从 中删除/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en/references/architecture/recipes/hermit.md"
。
我输入的字符串$pathname
是:
references/architecture/recipes/hermit.md
category="${pathname%/*}"
上面的行将删除/
路径中最后一个找到的所有内容:references/architecture/recipes/hermit.md
所以这里删除的是/hermit.md
并且$category
将包含:
references/architecture/recipes
title="${pathname##*/}"
上面的行将删除/
路径中最后一个找到的之前的所有内容:
references/architecture/recipes/hermit.md
所以这里删除的是:references/architecture/recipes/
。那么遗嘱$title
将包含:
hermit.md