Reputation: 641
I need to find out if a file or directory name contains any extension in Unix for a Bourne shell scripting.
The logic will be:
This is my first question in SO so will be great to hear from someone.
Upvotes: 3
Views: 553
Reputation: 189357
The concept of an extension isn't as strictly well-defined as in traditional / toy DOS 8+3 filenames. If you want to find file names containing a dot where the dot is not the first character, try this.
case $filename in
[!.]*.*) filename=${filename%.*};;
esac
This will trim the extension (as per the above definition, starting from the last dot if there are several) from $filename
if there is one, otherwise no nothing.
If you will not be processing files whose names might start with a dot, the case
is superfluous, as the assignment will also not touch the value if there isn't a dot; but with this belt-and-suspenders example, you can easily pick the approach you prefer, in case you need to extend it, one way or another.
To also handle files where there is a dot, as long as it's not the first character (but it's okay if the first character is also a dot), try the pattern ?*.*
.
The case
expression in
pattern )
commands ;; esac
syntax may look weird or scary, but it's quite versatile, and well worth learning.
Upvotes: 4
Reputation: 1646
I would use a shell agnostic solution. Runing the name through:
cut -d . -f 1
will give you everything up to the first dot ('-d .' sets the delimeter and '-f 1' selects the first field). You can play with the params (try '--complement' to reverse selection) and get pretty much anything you want.
Upvotes: 0