Extract Sub-Directory Path from Partially Known Directory
Let's start with your filename:
$ f=base/app/main/sub/first/tib1.ear
To extract the base name:
$ echo "${f##*/}"
tib1.ear
To extract the desired part of the directory name:
$ g=${f%/*}; echo "${g#base/app/}"
main/sub/first
${g#base/app/}
and ${f##*/}
are examples of prefix removal. ${f%/*}
is an example of suffix removal.
Documentation
From man bash
:
${parameter#word} ${parameter##word} Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``#'' case) or the longest matching pattern (the ``##'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter%word} ${parameter%%word} Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``%'' case) or the longest matching pattern (the ``%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable sub‐ scripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
Alternatives
You may also want to consider the utilities basename
and dirname
:
$ basename "$f"
tib1.ear
$ dirname "$f"
base/app/main/sub/first
creating the test files
mkdir -p base/app/main/sub/{first,second}
touch base/app/main/sub/first/tib1.{ear,xml}
touch base/app/main/sub/second/tib2.{ear,xml}
finding the ear files with bash
shopt -s globstar nullglob
ear_files=( base/**/*.ear )
printf "%s\n" "${ear_files[@]}"
base/app/main/sub/first/tib1.ear
base/app/main/sub/second/tib2.ear
Iterate over the array and use John1024's answer to extract the necessary info from each path.
for f in "${ear_files[@]}"; do ...; done