bash - string / file name manipulation
Posted by rolf on Thursday, 5 March 2015
In the following some useful bash snippets to manipulat strings / file names are listed.
Extract substrings
1. crop a consecutive substring ${string:position:length}
name=abcd123FGHI; subStr=${name:4:3}; echo $subStr; # result is 123
2. remove beginning or end of a string
str=/path/to/my/file/123_complicated_9034.txt;
removes shortest matching suffix pattern %
withoutEnding=${str%.txt}; # echo $withoutEnding; $ out: /path/to/my/file/123_complicated_9034
removes longest matching suffix pattern %%
withoutEnding2=${str%%_*}; echo $withoutEnding2; # out: /path/to/my/file/123
removes shortest matching prefix pattern #
withoutStart=${str#/path}; echo $withoutStart; # out: /to/my/file/123_complicated_9034.txt
removes longest matching prefix pattern ##
withoutStart2=${str##/*/}; echo $withoutStart2; # out: 123_complicated_9034.txt
blog_external_links:
Add new comment