I am using for testing purposes 2 lines with and without the optional suffix (last 2 enumerated elements ,D2,E2).
echo -e "A1,B2,C2\nA2,B2,C2,D2,E2" | sed -E 's/^(.*),(.*),(.*)((,.*)(,.*)){0,1}$/[\1],\2,\3\5\6/'
[A1],B2,C2
[A2,B2,C2],D2,E2
where I would like to obtain
[A1],B2,C2
[A2],B2,C2,D2,E2
I simply want to make the last 2 components optional and append them at the end in case they are found.
I tried with repetitions {x,y}, with question mark (?), but I don't manage to make really optional the 2 last elements on the sed find pattern. Looks like the sed greediness is extremely greedy because I am wrapping the pattern with '^' and '$' and instead of attempting first the unoptional pattern, it just takes the optional one with very greedy first component..
NOTE: The regex is a simplification of my real need so overcoming by different approaches might be futile. I really want to do it with sed and this particular approach, since this is just to improve my knowledgement on the tricks of the tool
EDIT: Thanks for the answers, this was my goal
sed -E 's/^([^,]*),([^,]*),([^,]*)(,[^,]*)?(,[^,]*)?$/[\1],\2,\3\4\5/'
sed 's/^\([^,]*\)/[\1]/'
gives the output you show, but I'm not sure I completely understand you.