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. ...

Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.