Hakkim Ansari Hakkim Ansari - 3 months ago 8
Bash Question

Need shell script to extract sub-string starting with a pattern

I have to extract sub-string starting with a pattern

"Branch_"
.

Sample IO

Input1: /home/user/Branch_1.1/fsw/make
Output1: /home/user/Branch_1.1

Input2: /home/user1/code/Branch_1.1_new/new_dir/code_changes
Output2: /home/user1/Branch_1.1_new

Input3: /home/john/project/new/Branch_5.6_code/make/files
Output3: /home/john/project/new/Branch_5.6_code

Input4: /home/danny/Branch_code/new_files/make
Output4: /home/danny/Branch_code


Thanks in advance.

Answer

You can use bash regex for this:

s='/home/john/project/new/Branch_5.6_code/make/files'    
[[ $s =~ ^(.*/Branch_[^/]*).* ]] && echo "${BASH_REMATCH[1]}"

/home/john/project/new/Branch_5.6_code

s='/home/danny/Branch_code/new_files/make'
[[ $s =~ ^(.*/Branch_[^/]*).* ]] && echo "${BASH_REMATCH[1]}"

/home/danny/Branch_code