Sed replace using same pattern repeating multiple times in a line
I have text like below in a file:
I am trying to replace the above line to following
How can I acheive this?
I am able to do it if the occurrence is for 1 time:
But If I try like below
I am getting like this:
I have to limit it to every occurrence of the pattern.
Thanks for your help.
agama
October 15, 2012, 8:15pm
2
You're falling victim to the greedy match. Have a go with this:
echo "/*<tagz>*/${tagz}.unix some random text and /*<tag1>*/${tag}.unix" | sed -E 's!\*<([^>]*)>[^.]*\.!*<\1>*/${\1}.!g'
Only tried it on your sample and one other contrived example, so it might not be perfect. I also prefer using -E to avoid escaping parens which just make it messy. If you are using a BSD based sed it'll be a different (-r or -R, I cannot remember and my BSD box isn't up right now).
I don't see the pattern you're trying to match nor the desired change you want from your example. You seem to say that you want to change
/*<tagz>*/hello.
to:
/*<tagz>*/${tagz}.
which I can easily make happen, but then you want the same substitution command to change
/*<tag2>*/bye.
to:
/*<tag1>*/<tag>.
which seems entirely different.
Please describe in words the pattern you are trying to match and describe the replacement that you want to make for that pattern.
Sorry for the typo:
I am trying to match the pattern
hello and bye are not same always, there can be anything in place hello and bye.
I am trying to remember the value and repalce it like below:
---------- Post updated at 07:54 PM ---------- Previous update was at 07:51 PM ----------
agama:
You're falling victim to the greedy match. Have a go with this:
echo "/*<tagz>*/${tagz}.unix some random text and /*<tag1>*/${tag}.unix" | sed -E 's!\*<([^>]*)>[^.]*\.!*<\1>*/${\1}.!g'
Only tried it on your sample and one other contrived example, so it might not be perfect. I also prefer using -E to avoid escaping parens which just make it messy. If you are using a BSD based sed it'll be a different (-r or -R, I cannot remember and my BSD box isn't up right now).
-E illegal option
OK. The following should work with any sed that conforms to the standards:
sed 's|/\*<\([^>]*\)>\*/[^.]*.|/*<\1>*/${\1}.|g'