Lukasz Kujawa
Lukasz Kujawa

Reputation: 3096

parameter expansion with substitution in bash

I have a trivial problem with regular expression in bash.

#!/bin/bash
FNAME=$1
echo ${FNAME//.*\/tests\//}

I want to remove everything before /test/ including the /test/ as well. Because of some reasons ".*" doesn't work.

$ ./eclipse/unittest.sh /foo/tests/bar
/foo/tests/bar

How do I select anything in bash reg exp?

Upvotes: 0

Views: 128

Answers (1)

rob mayoff
rob mayoff

Reputation: 385500

You can use # followed by a pattern to remove everything up to and including the pattern. It will use the shortest match:

function f {
    echo ${1#*/tests/}
}

$ f /foo/tests/bar
bar
$ f /foo/tests/bar/tests/last
bar/tests/last

If you want to use the longest match, you can use ##:

function f {
    echo ${1##*/tests/}
}

$ f /foo/tests/bar
bar
$ f /foo/tests/bar/tests/last
last

Upvotes: 3

Related Questions