Reputation: 1249
I have a string like this:
chair melon cow pushing danced chair chair pushing cow danced
I want to have sed replace the first occurrence of chair
the first time around:
REPLACED melon cow pushing danced chair chair pushing cow danced
then the second:
chair melon cow pushing danced REPLACED chair pushing cow danced
and then the third:
chair melon cow pushing danced chair REPLACED pushing cow danced
I can create the loop and +1 increase myself, I just need to know if sed (BSD or GNU doesn't matter) allows for something like this by specifying an integer.
Almost like: sed $number',/chair/{s/chair/REPLACED/}'
, even though that would not work the way I want. I just put that there to show that I'm looking to input an integer from variable.
I don't mind using awk
but really, really prefer not to.
Upvotes: 1
Views: 1031
Reputation: 133650
Could you please try following. If I got your question correctly, following will substitute 1st occurrence of chair
only. Tested and written with GNU sed
.
echo "chair melon cow pushing danced chair chair pushing cow danced" |
sed 's/chair/REPLACE/1'
NOTE: One important point to be noted here, lets say you have run this command 1st time and replaced very first occurrence of chair then in next try you want to substitute 2nd occurrence which has become now 1st occurrence of chair since 1st one was already replaced with new text, so be careful while using it. Thought to mention it here.
Upvotes: 2