Now I have a string str="…AAA…", I want to split it to 3 substring variables sub1 sub2 sub3 the AAA is sub2 and is an unique pattern which won’t appear in sub1 and sub3. And all the other characters were saved in sub1 and sub3. Only one extreme situation is that AAA may appear at the end when sub3 needs to be a void string. How can I achieve this, maybe using grep, sed or gawk?
>Solution :
You don’t need grep, sed, or awk. Just use Shell Parameter Expansion with % and #:
str="ABCAAAXYZ"
sub2="AAA"
sub1="${str%${sub2}*}"
sub3="${str#*${sub2}}"
printf '%s\n' "$sub1" "$sub2" "$sub3"
ABC
AAA
XYZ
This works just the same with str="ABCAAA" or str="AAAXYZ".