shell

Strings in bash

Start with a string:

$ a="hi, this is my beautifull string"

Positional substrings:

  1. Substring from the 4th character on:
    $ echo ${a:3}
    this is my beautifull string
    
  2. Substring of length 4 from the 10th character:
    $ echo ${a:9:4}
    is m
    

Substring modification:

  1. Substitute the first instance of a substring:
    $ echo ${a/full/ful}
    hi, this is my beautiful string
    
  2. Same example:
    $ echo ${a/h/H}
    Hi, this is my beautifull string
    
  3. Substitute all the instances of a substring:
    $ echo ${a//hi/HI}
    HI, tHIs is my beautifull string
    

Substring removal:

  1. Remove the shortest match of a substring from the start:
    $ echo ${a#h*i}
    , this is my beautifull string
    
  2. Same, starting at the end
    $ echo ${a%i*g}
    hi, this is my beautifull str
    
  3. Remove the longest match of a substring from the start:
    $ echo ${a##h*i}
    ng
    
  4. Same, starting at the end
    $ echo ${a%%i*g}
    h
    

These are for bash-2, they probably work on bash-3 and they seem to work on ksh (under OS X at least).

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields