I have a script like this:
for html in ./templates/*.html
do
# Here I need only the file name without extension.
done
How can I get only the file name without extension in the loop?
EDIT : I'm very new to UNIX.
I have a script like this:
for html in ./templates/*.html
do
# Here I need only the file name without extension.
done
How can I get only the file name without extension in the loop?
EDIT : I'm very new to UNIX.
Use basename
:
basename "$html" .html
Alternatively, a bash regular expression can be used to break the path into the directory prefix, basename, and file suffix:
$ [[ "/usr/share/doc/bzip2-devel-1.0.6/manual.html" =~ (.+/)?([^/]+)(\.[^/]+) ]]; echo ${BASH_REMATCH[*]}
/usr/share/doc/bzip2-devel-1.0.6/manual.html /usr/share/doc/bzip2-devel-1.0.6/ manual .html
^ ^ ^ ^
| | | |
entire string directory base suffix
To remove just the extension, and leave the path and name, use the right pattern matching operator:
for f in ./templates/*.html; do
echo ${f%%.html}
done
The %%
operator matches a substring starting from the right of the variable, and returns the rest. So it effectively matches and removes the suffix, which is very useful for file extensions.
So ./templates/index.html
will simply return ./templates/index
. You can add your own suffix or extension as required.
This is a little more efficient than invoking basename
for every file, as it avoids the overhead of spawning another process.
Try this
for html in ./templates/*.html do echo $html|sed 's/\.[a-zA-Z]*$//g'; done