bash - string / file name manipulation

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_tags: 

Add new comment

Filtered HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <img> <br> <p> <span>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Use [collapse] and [/collapse] to create collapsible text blocks. [collapse collapsed] or [collapsed] will start with the block closed.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • Code snippets in <code>...</code> or <source>...</source> automatically will be pretty printed.
  • Use [collapse] and [/collapse] to create collapsible text blocks. [collapse collapsed] or [collapsed] will start with the block closed.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Target Image