Slicing filenames based on extension
Several shell scripts perform manipulations based on filenames. We may need to perform actions such as renaming the files by preserving the extension, converting files from one format to another (change the extension by preserving the name), extracting a portion of the filename, and so on. The shell comes with inbuilt features for slicing filenames based on different conditions. Let us see how to do it.
How to do it…
The name from name.extension
can be easily extracted using the %
operator. You can extract the name from "sample.jpg"
as follows:
file_jpg="sample.jpg" name=${file_jpg%.*} echo File name is: $name
The output is:
File name is: sample
The next task is to extract the extension of a file from its filename. The extension can be extracted using the #
operator as follows:
Extract .jpg
from the filename stored in the variable file_jpg
as follows:
extension=${file_jpg#*.} echo Extension is: jpg
The output is:
Extension is: jpg
How it works…
In the first task...