How to Extract Filename & Extension in Shell Script

Channel: Linux
Abstract: /bin/bash fullfilename="/var/log/mail.log"filename=$(basename "$fullfilename")fname="${filename%.*}"echo $fname 3. Get Extension Only Now extract file

Some times you may require to extract filename and extension in different variables to accomplished a task in bash shell programming. This article will help you to extract filename and file extension from a full file name or path.

Let’s follow the below steps:

1. Get filename without Path

First remove the full file path from input filename. For example if filename input is as /var/log/mail.log then extract full filename ail.log only.

#!/bin/bash fullfilename="/var/log/mail.log" filename=$(basename "$fullfilename") echo $filename12345#!/bin/bash fullfilename="/var/log/mail.log"filename=$(basename "$fullfilename")echo $filename

2. Filename without Extension

Now extract filename without an extension from extracted full filename without a path as above.

#!/bin/bash fullfilename="/var/log/mail.log" filename=$(basename "$fullfilename") fname="${filename%.*}" echo $fname123456#!/bin/bash fullfilename="/var/log/mail.log"filename=$(basename "$fullfilename")fname="${filename%.*}"echo $fname

3. Get Extension Only

Now extract file extension without name from extracted full filename without path.

#!/bin/bash fullfilename="/var/log/mail.log" filename=$(basename "$fullfilename") ext="${filename##*.}" echo $ext123456#!/bin/bash fullfilename="/var/log/mail.log"filename=$(basename "$fullfilename")ext="${filename##*.}"echo $ext

4. Testing

Finally, test all the things in a single shell script. Create a new script file using the following content. The filename will be passed as a command line argument during the script execution.

#!/bin/bash fullfilename=$1 filename=$(basename "$fullfilename") fname="${filename%.*}" ext="${filename##*.}" echo "Input File: $fullfilename" echo "Filename without Path: $filename" echo "Filename without Extension: $fname" echo "File Extension without Name: $ext"1234567891011#!/bin/bash fullfilename=$1filename=$(basename "$fullfilename")fname="${filename%.*}"ext="${filename##*.}" echo "Input File: $fullfilename"echo "Filename without Path: $filename"echo "Filename without Extension: $fname"echo "File Extension without Name: $ext"

Let’s execute the script with filename as command line argument. Make sure to enclose in double quote if any of the directory or filename have space in it.

./script.sh "/var/log/mail.log" 

Input File:  /var/log/mail.log
Filename without Path: mail.log
Filename without Extension: mail
File Extension without Name: log

Ref From: tecadmin

Related articles