Substring extraction in bash

Revision history
Tags: bash

To extract substrings from variables in bash, we can use the following syntax

${variable_name:offset:length}

Caveats:

Get the file extension of a filename

$ filename=foobar.txt
$ echo ${filename: -4}
.txt

Get the file name without extension

$ filename=foobar.txt
$ echo ${filename:0: -4}
foobar

References

If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom).

Did you find any typos, incorrect information, or have something to add? Then please propose a change to this post.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.