Search code examples
bashvariablessed

Bash delete all symbols before last 2 "/" symbols in variable


Struggling. Please help.

a="/var/www/test/some/page3.html"

I need to transform it to

a="some/page3.html"

I'm trying

a=$(sed "s~/var/www/test/~~g" $a)

But getting baaaad results.


Solution

  • Bash parameter parsing.
    No need to run a subprocess.

    If you know exactly what needs to be trimmed -

    $: echo "${a#/var/www/test/}"
    some/page3.html
    

    If you maybe don't know the exact path-string or even how many subdirectories to take off the front, but know exactly how much to keep on the rear, use one string parse to adjust another.

    You can get the part you want to remove in one variable parse -

    $: echo "${a%/*/*}"        # the part you want to get rid of
    /var/www/test
    

    So use that to get the remainder, all in one line.

    $: echo "${a#${a%/*/*}/}"  # strip the above, and the next slash
    some/page3.html
    

    If you are more comfortable with a regex, it's still easy to do with two steps in one line.

    $: [[ "$a" =~ ([^/]+/[^/]+)$ ]] && echo "${BASH_REMATCH[1]}"
    some/page3.html