-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,215
  • 3
  • 17
  • 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
  • 131,725
  • 17
  • 180
  • 271
  • And try `"$(basename "$html" .html)"` in case you want to use the result in another command. – Alfe Sep 27 '13 at 12:33
  • This is returning me **default_template.html** – Nagendra Varma Sep 27 '13 at 12:34
  • from `info basename` `If SUFFIX is specified and is identical to the end of NAME, it is removed from NAME as well.` So you need to call as @Alfe mentioned, `basename $html .html` – abasu Sep 27 '13 at 12:39
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
  • 19,278
  • 3
  • 45
  • 60
0

Try this

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