Q:

Regular expression for moving file

I have this code in shell script. What it does is that it removes all extensions including dots (.) in a file name and returns just the name, like so /home/user/filename. But the problem is that I want it to remove even the directory structure and return just the file name like this filename.
Here's the code that removes only the extension.
filename="/home/user/filename.php.txt.doc"      
newname=${filename%%.*}
echo $newname
/home/user/filename

Is there a way of getting just the file name and not with the directory extension included?
filename

Thanks

A:

Try "${filename##*/}" to get the name of the file.
$ filename="/home/user/filename.php.txt.doc"      
$ newname=${filename%%.*}
$ newname=${newname##*/}
$ echo $newname
filename

Alternatively, use basename:
$ filename="/home/user/filename.php.txt.doc"      
$ newname="$(basename ${filename%%.*})"
$ echo $newname

You can also do it with a single sed command, but it is a bit unreadable, so I wouldn't:
$ sed 's|.*/\([^\.]*\).*|\1|g' <<< "$filename"
filename

