-1

Basically, I'd like to write a bash script or function where given an input of a/b/c/d, it would return all matches where each path component had wildcards at the start and end, e.g. *a*/*b*/*c*/*d*. It would be nice to respect the tilde (~) as home folder as well.

Is there an easy way to do this in bash or do I need to do this in something like Python?

  • 2
    Some more examples would be useful. Also, the `~` expansion feature will be a hassle to implement, I think. – Tom Fenech Jan 08 '16 at 16:03

1 Answers1

2

I'll give you a starting point:

x="a/b/c/d"                                                                     
x="*${x//\//*\/*}*"                                                             
echo $x
# output: "*a*/*b*/*c*/*d*", or all matching paths (if any)

This solution is far from perfect. Specifically you'd have to solve the following problems:

  • x may contain special characters like spaces or * characters. They need to be properly escaped.
  • x may contain double slashes. For example: x=a//b. I think you want it to become *a*/*b*, not *a*/**/*b*.
  • x may contain leading or trailing slashes. For example: x=/a/b or x=a/b/.
  • x may start with a tilde.

All these problems may be solved with if statements and replacements.


Another approach (that requires more code, but is probably safer and less error prone) is to parse and interpret the string with a loop, like this:

shopt -s nullglob

x="a/b/c/d"
IFS=/ read -a x <<< "$x"
# x is now an array in the form (a b c d)

result=(*"${x[0]}"*)

for c in "${x[@]:1}"
do
    newresult=()
    for r in "${result[@]}"
    do
        match=("$r"/*"$c"*)
        [ "${#match[@]}" -gt 0 ] && \
            newresult=("${newresult[@]}" "${match[@]}")
    done
    result=("${newresult[@]}")
done

echo "${result[@]}"

Again, this is not perfect. Problems include:

  • You have to deal with double slashes.
  • You have to deal with leading and trailing slashes.
  • You still have to deal with the tilde.

This solution is nice because these problems are easier to handle, also you don't have to worry about special characters.

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69