Get filename and or extension

This script uses the filename and the extension of a file using shell scripts. This is useful when you have to rename a file or its extension.

 
#!/bin/sh
# Name:      filenameextension.sh
# Author:    kdguntu@gmail.com
# Function:  Show filename and extension
# Copyright: 2010 kdguntu@gmail.com GNU GPL v3
#            http://www.gnu.org/licenses/gpl.html
 
FILE="./test.txt"
FILE_NOPATH="`basename $FILE`"
EXTENSION1="${FILE_NOPATH##*.}"
NAME1="${FILE_NOPATH%.*}"
EXTENSION2=`echo "$FILE_NOPATH" | cut -d'.' -f2`
NAME2=`echo "$FILE_NOPATH" | cut -d'.' -f1`
NEWEXTENSION="$NAME1.csv"
 
echo "$FILE without PATH is $FILE_NOPATH"
echo "Name:$NAME1 Extension:$EXTENSION1" # best solution
echo "Name:$NAME2 Extension:$EXTENSION2"

Only the “best solution” works also for files named a.b.c or .c

This entry was posted in bash, cut, linux, macosx, ubuntu and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *