特定の文字の後の文字を取得する方法

特定の文字の後の文字を取得する方法

変数WORKSPACEがあります。/Users/shinichiokada/Bash_Projects/markdown-docs-as-pdf/.vivliostyle/tauri/en

各行からそれらを削除し、2つの変数を作成したいと思います。

たとえば、オンラインで検索してみると

"/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

など。

以下を試しましたが、最後の2つのアイテムのみを取得します。

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

おすすめ記事