bash variables magic

bashlove

I often find myself searching for a, say, left() or mid() function when coding bash. Somehow my subconscious mind seems to know I’m doing too much in bash and therefore tends to forget things like a simple left() in bash. So I note them here. Lets hope I don’t forget where I wrote that down…

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!

Did I miss one?

5 Comments

  1. Love this, bookmarked.

    The last one will really cut down my use of sed and pipes in the middle of my scripts. :)

  2. Please make sure you double-quote your expansions in your examples; otherwise, terrible things can happen!

    Explanation: http://www.reddit.com/r/sysadmin/comments/1qxg0h/bash_variables_magic_left_right_mid_and_len_in/cdhtqkv
    See also: http://mywiki.wooledge.org/Quotes

  3. admin

    19.11.2013 at 08:49

    You are completely right! I updated the post accordingly!

    Thanks!

  4. There’s also the remove matching prefix and suffix pattern operations:

    shortest prefix:
    echo ${var#*l} –> “lo, world!”
    longest prefix:
    echo ${var##*l} –> “ld!”

    shortest suffix:
    echo ${var%l*} –> “Hello, wor”
    longest suffix:
    echo ${var%%l*} –> “He”

    hope this won’t completely break due to comment restrictions ;)

    tl;dr: there’s prefix and suffix matching for removing parts of strings, my use case is stripping file name extensions mostly

  5. mr51m0n

    19.11.2013 at 12:35

    Uhhhh, I’ll do a followup post including them! Thanks!

Leave a Reply

Your email address will not be published.

*

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

© 2014 netmess

Theme by Anders NorenUp ↑