O'Reilly logo

Linux Shell Scripting Cookbook by Sarath Lakshman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Slicing filenames based on extension

Several custom shell scripts perform manipulations based on file names. We may need to perform actions like renaming the files by preserving extension, converting files from one format to another (change the extension by preserving the name), extracting a portion of the file name, and so on. The shell comes with inbuilt functionalities for slicing filenames based on different conditions. Let's see how to do it.

How to do it…

The name from name.extension can be easily extracted by 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required