Slicing filenames based on extensions
Many shell scripts perform actions that involve modifying filenames. They may need to rename the files and preserve the extension, or convert files from one format to another and change the extension, while preserving the name, extracting a portion of the filename, and so on.
The shell has built-in features for manipulating filenames.
How to do it...
The % operator will extract the name from name.extension. This example extracts sample from sample.jpg:
file_jpg="sample.jpg"
name=${file_jpg%.*}
echo File name is: $name The output is this:
File name is: sampleThe # operator will extract the extension:
Extract .jpg from the filename stored in the file_jpg variable:
extension=${file_jpg#*.}
echo Extension is: jpg The output is as follows:
Extension is: jpgHow it works...
To extract the name from the filename formatted as name.extension, we use the % operator.
${VAR%.*} is interpreted as follows:
- Remove the string match from
$VARfor the wildcard pattern that appears...