Below is the step by step details:
1. Get Filename without Path:
First remove the full file path from input filename. For example if filename input is as /etc/apache2/apache2.conf then extract full filename apcahe2.conf only.#!/bin/bash fullfilename="/etc/apache2/apache2.conf" filename=$(basename "$fullfilename") echo $filename
2. Filename without Extension:
Now extract filename without extension from extracted fullfilename without path as above.#!/bin/bash fullfilename="/etc/apache2/apache2.conf" filename=$(basename "$fullfilename") fname="${filename%.*}" echo $fname
3. File Extension without Name:
Now extract file extension without name from extracted fullfilename without path.#!/bin/bash fullfilename="/etc/apache2/apache2.conf" 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 following content. Filename will be passed as command line argument during executing script.#!/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"Let’s execute the script with filename as command line argument.
$./script.sh /etc/apache2/apache2.conf Input File:/etc/apache2/apache2.conf Filename without Path:apache2.conf Filename without Extension:apache2 File Extension without Name:conf
Comments
Post a Comment