-4

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.

Nagendra Varma
  • 2,046
  • 3
  • 16
  • 26

3 Answers3

4

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
Maxim Egorushkin
  • 125,859
  • 15
  • 164
  • 254
0

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.

gavinb
  • 18,233
  • 3
  • 44
  • 55
0

Try this

for html in ./templates/*.html
do
   echo $html|sed 's/\.[a-zA-Z]*$//g';
done