Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Split filename.ext into filename and .ext 2

Status
Not open for further replies.

Calator

Programmer
Feb 12, 2001
262
AU
In a ksh shell script, I need to split a filename into two components : the name and the extension.

Apart from the simple case, this should be able to handle situations like: files with no extension; files where the dot appears for more than once. Examples:

filename.ext file_name="filename" file_ext=".ext"

filename file-name="filename" file_ext=""

filename.my.file.ext file_name="filename.my.file"
file_ext=".ext"

Could anyone supply some simple code to achive this?
 
[tt]
file_name=$(echo $file|awk '{gsub(/\.[^.]*$/,"")}1')
file_ext=$(echo $file|awk 'gsub(/^.*\./,"")')
[/tt]
 
It depends if you're using real ksh92 or some clone, like pdksh.

Code:
[ksh]$ filename=qwer.asdf.zxcv 
[ksh]$ echo ${filename%.*}     
qwer.asdf
[ksh]$ echo ${filename##*.}
zxcv
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top