User Tools

Site Tools


blog:bash_string_functions

bash snippets

String function

len() in bash

$ var='Hello, World!'
$ echo "${#var}"
13

left() in bash

$ var='Hello, World!'
#${string:position:length}
$ echo "${var:0:5}"
Hello

right() in bash

$ var='Hello, World!'
#${string:position:length}
$ echo "${var:7:${#var}}"
World!
#or a litte more dynamic.. (the 6 most right chars)
echo "${var:$((${#var}-6)):${#var}}"
World!

mid() in bash

$ var='Hello, World!'
#${string:position:length}
$ echo "${var:4:4}"
o, W

string replace first in bash (substitute)

$ var='Hello, World!'
#${string/substring/replacement}
$ echo "${var/o/a}"
Hella, World!

string replace all in bash (substitute)

$ var='Hello, World!'
#${string//substring/replacement}
$ echo "${var//o/a}"
Hella, Warld!

Reference: http://www.netmess.org/tag/bash/

~~LINKBACK~~

Discussion

Enter your comment. Wiki syntax is allowed:
  _____  _      __   __ __   ____  __  __
 / ___/ | | /| / /  / //_/  /  _/ / / / /
/ (_ /  | |/ |/ /  / ,<    _/ /  / /_/ / 
\___/   |__/|__/  /_/|_|  /___/  \____/
 
blog/bash_string_functions.txt · Last modified: 2014-04-24 09:45 by brb