需要shell脚本来提取以模式开头的子字符串

时间:2016-08-29 16:29:32

标签: linux bash shell sh

我必须从模式"Branch_"开始提取子字符串。

示例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

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用bash正则表达式:

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