If you want to safely determine the length of a string with bash, you should use parameter expansion. ls
alone is only capable of glob syntax, which (likely) cannot do what you want. find
has different implementations on BSD and some Linuxes and -regextype
isn't necessarily a legal flag. The good news is, bash has loops, and these can give you what you want.
for filename in * # globs all files in your directory.
do
clip=${filename%.*} # excludes the first extension
if [[ ${#clip} -eq 5 ]] # test the length of the remaining string
then
ls -d $filename # call ls to show you the file or directory
fi
done
If instead you need any filename solely with five alphanumeric chars, your method and other answers will only return those files which begin with five chars. For example:
Using ls [a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9]
five1.txt # matches
fi_ve.txt # fails
a.pages # fails
q_fiver.txt # fails
To include any file with any five-character long alphanumeric string, and only those with any five-character long alphanumeric string, you can use grep
's more universal regex implementation under bash. Although I wouldn't normally recommend it, the use of the \w
and \W
here can help readability a great deal (where \w
= [[:alnum:]]
and \W
= [^[:alnum:]]
– but they will include underscores, so use at peril).
for filename in *
do
if (grep -qE '(^|\W)\w{5}($|\W)' <<<"$filename")
then
ls -d "$filename"
fi
done
ls
… instead of regex”? If this is an actual constraint, you should [edit] it into the question rather than just mention it in a comment. (2) If n=5, why are you repeating the[a-zA-Z0-9]
regex seven times? – G-Man Says 'Reinstate Monica' Feb 15 '16 at 22:17