Search code examples
zsh

how to capture text after / but before 2nd - symbols in zsh


For example I have a git branch name feature/ABC-123-my-stuff

I want to just capture ABC-123 in this format.

I tried

cut -d "/" -f2 <<< "$branchName"

result in

ABC-123-my-stuff

but I want to only keep the string right after the / and before 2nd -

What do I add / modify to achieve that?

NOTE: I am using zsh on MacOS


Solution

  • Use cut 2 times:

    (cut -d"/" -f2 | cut -d"-" -f1,2) <<< $branchName
    

    or with echo:

    echo $branchName | cut -d"/" -f2 | cut -d"-" -f1,2
    

    Another way you can use grep:

    echo $branchName | egrep -o '[A-Z]{3}-[0-9]{3}'
    

    Note: this solution will work if you have every time 3 times capital letter, then -, then 3 digits.

    All solutions gives me the output:

    ABC-123