You can do it simply with awk
matching the last set of word characters in each field and outputting them, e.g.
awk '{for (i=1; i<=NF; i++) if ($i ~ /folderA/) { match($i,/\w+$/); print substr($i,RSTART,RLENGTH)}}' <<< $path_str
Example Use/Output
path_str="path/folderA/fileA1 path/folderA/subFolderA/fileA2 path/folderB/fileB1"
awk '{for (i=1; i<=NF; i++) if ($i ~ /folderA/) { match($i,/\w+$/); print substr($i,RSTART,RLENGTH)}}' <<< $path_str
fileA1
fileA2
You can adjust the output format as desired. If you want the output all on one line, or if you want to use command substitution to capture the output in a new array, it's up to you.
Using Bash Parameter Expansions
If you want to use parameter expansions with substring removal, you can use a simple loop and the expansion $(var##*/}
to remove everything up to the final '/'
from each path component, e.g.
path_str="path/folderA/fileA1 path/folderA/subFolderA/fileA2 path/folderB/fileB1"
for i in $path_str; do
[[ $i =~ folderA ]] && echo ${i##*/}
done
fileA1
fileA2
For your case the parameter expansion is likely the most efficient as it is a built-in to your shell and avoids spawning a subshell. However, if you had hundreds of thousands of components, I'd probably let awk
handle it then.
The set of POSIX compliant parameter expansions with substring removal are:
${var#pattern} Strip shortest match of pattern from front of $var
${var##pattern} Strip longest match of pattern from front of $var
${var%pattern} Strip shortest match of pattern from back of $var
${var%%pattern} Strip longest match of pattern from back of $var
Bash provides many, many more parameter expansion in addition to those provided by POSIX. Including everything from substring replacement to character case conversion.
Let me know if you have further questions.