To see all files that matches the pattern /foo/bar/a.b.c.d.*
, use
printf '%s\n' /foo/bar/a.b.c.d.*
To see all files that matches the pattern /foo/bar/a.b.c.[helloworld].*
, where [hellowerld]
is literal, use
printf '%s\n' /foo/bar/a.b.c.'[helloworld]'.*
I.e., quote the parts of the pattern that need to be literal.
If you get the string a.b.c.[helloworld].x
and you want to see all files under /foo/bar
that matches the pattern that you get if you remove the last .x
and replace it with .*
, use
string='a.b.c.[helloworld].x'
printf '%s\n' /foo/bar/"${string%.*}".*
The only thing you need to think about here is to quote the expansion of the variable substitution.
Would you want to do this in the bash
shell, recursively, and include hidden names, then use
shopt -s globstar dotglob
string='a.b.c.[helloworld].x'
printf '%s\n' /foo/bar/**/"${string%.*}".*
Your function could probably be written (without searching in subdirectories) as
findSiblingFiles () {
printf '%s\n' "${1%.*}".*
}
or, to have it output nothing, not even a blank line, if the pattern does not match,
findSiblingFiles () (
shopt -s nullglob
set -- "${1%.*}".*
[ "$#" -gt 0 ] && printf '%s\n' "$@"
)
Note that since we are only modifying the first argument's "tail", we don't need to separate the filename from the directory path, unless we want to verify that there's actually a dot in the given filename, which the following code does.
findSiblingFiles () (
shopt -s nullglob
if [[ ${1##*/} != *.* ]]; then
echo 'Filename has no suffix' >&2
return 1
fi
set -- "${1%.*}".*
[ "$#" -gt 0 ] && printf '%s\n' "$@"
)
Testing:
$ findSiblingFiles ~myself/local/src/project/doc/document.txt
/home/myself/local/src/project/doc/document.man
/home/myself/local/src/project/doc/document.mdoc
/home/myself/local/src/project/doc/document.txt
filePath='a.b.c.[helloworld].x' && basename "${filePath%.*}"
outputsa.b.c.[helloworld]
- so if it's wrong then what did you expect?find
?find
although that's my current approach. I'm looking for a general (and not overly convoluted) way to find files in the same folder with alternate extensions, that doesn't choke on square brackets (or other characters)