Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: string match simplification?



First, think about the way the `#` and `%` operators work: they _remove_ matching strings from the parameter value when expanding it. So if there is no matching string, they don't remove anything. That seems completely intuitive; it would be weird for it to remove _everything_ when there's no match. 

If your goal is to extract the extension if there is one, you might be better served by a regex match.

[[ $filename =~ '\.(.*)' ]]

extension=$match[1]


That way, $extension be empty if there's no extension.

On Tue, Sep 3, 2024 at 11:53 AM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
I'm wanting to cut filenames at the extension, if any, but only if it's a 'real' extension.  Dunno if there's any formality to the idea but whereas you can put a period anywhere in a filename, we do recognize 'real' extensions like '.eml', '.html' '.png' ... and so on.  Seems to me that real extensions are almost never longer than four characters, say five to be safe.  Anyway the code below seems fine, but it bothers me that if there's no extension at all the variable 'extension' gets set to the entire string whereas I'd expect if there's no match it would return null.  Why return an obviously incorrect answer?  So there's that line to kill $extension if no match.  It's a trivial issue but is there a less belabored way? 

#!/usr/bin/zsh

filename=$1
extension="${filename##*.}"
(( $#filename == $#extension )) && extension=
if (( $#extension > 0 && $#extension < 6 )); then
    filename="${filename%.*}"
else
    extension=
fi                                            
echo filename is: $filename
echo extension is: $extension



--
Mark J. Reed <markjreed@xxxxxxxxx>


Messages sorted by: Reverse Date, Date, Thread, Author