Differences between revisions 2 and 3
Revision 2 as of 2010-02-25 23:40:59
Size: 806
Editor: CarlNobile
Comment:
Revision 3 as of 2010-02-25 23:42:01
Size: 811
Editor: CarlNobile
Comment:
Deletions are marked like this. Additions are marked like this.
Line 37: Line 37:
345

BASH String Slice Like Python

This is a small shell function that does the same thing a Python slicing.

function string_slice {
  STRING="$1"
  declare -i LENGTH="${#STRING}"
  declare -i START="$2"
  declare -i END="$3"

  if [ $START -lt 0 ]; then
    START=$[ $LENGTH + $START ]
  fi

  if [ $END -le 0 ]; then
    END=$[ $LENGTH + $END ]
  fi

  START=$[ $START + 1 ]
  (echo "$STRING" | cut -c $START-$END) 2> /dev/null
}

Usage

$ string_slice "12345" 0 1
1
$ string_slice "12345" 0 3
123
$ string_slice "12345" 2 3
3
$ string_slice "12345" 2 -2
3
$ string_slice "12345" -3
345

Credits

I found this code on: String Slicing in BASH Like Python

BASHStringSlice (last edited 2010-02-25 23:42:01 by CarlNobile)