文字列のグループ内のどの文字列が別の文字列のプレフィックスであるかを判断する Bash コマンド

文字列のグループ内のどの文字列が別の文字列のプレフィックスであるかを判断する Bash コマンド

私がやろうとしていることは次のとおりです。コード リポジトリ用のフォルダーがあり、現在の作業ディレクトリの「コード ルート ディレクトリ」を判断できる bash コマンドを探しています。たとえば、現在 にいる場合~/repositories/my_program/folder1/folder2/、コマンドで を返すようにします~/repositories/my_program/

を使用すると作業ディレクトリのパスを取得できpwd、 を使用するとプロジェクトのリストを取得できます。のプレフィックスである文字列ls ~/repositories/を判別するにはどうすればよいですか?~/repositories/<match>pwd

答え1

の直下のディレクトリだけが必要な場合は~/repositories、次のようにします。

$ sed -r "s#($HOME/repositories/[^/]*).*#\1#" <<<$PWD
/home/terdon/repositories/my_program

印刷my_programのみの場合:

$ sed -r "s#$HOME/repositories/([^/]*).*#\1#" <<<$PWD
my_program

代わりに使用するには~/

$ sed -r "s#$HOME(/repositories/[^/]*).*#~\1#" <<<$PWD
~/repositories/my_program

アイデアは、 を一致させてから、もう 1 つのディレクトリ ( 以外の文字$HOME/repositories/の最長の文字列として定義されます: ) を一致させることです。/[^/]*

関連情報