Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split a string with an uniq substring in bash?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading