goose goose
goose goose

Reputation: 96

Using sed to replace only first ocurrence while using variable and "/" in variable

I have a file that looks like this

I/am/a/string
I'm/still/a/string
Always/a/string

I'm trying to use sed to replace the first occurrence of "string" with a variable that contains "/" like

x=ive/been/replaced

So the output of sed would be

I/am/a/ive/been/replaced

Because i only want the first occurrence and i'm using a variable typically you use

sed -i "0,/string/s//$x/" file  

However in this case because the variable has "/" i have to use a different separator like

sed "0,|string|s||$x|" file

But this does not work.

what am i missing?

NOTE:

I would like to accomplish this in sed

Upvotes: 1

Views: 105

Answers (1)

P....
P....

Reputation: 18371

If you are ok using awk: you can print and exit after first replacement.

awk -v x="${x}" '{gsub(/string/,x);print ;exit}' file
I/am/a/ive/been/replaced

sed version: This will exit after first match, note that search string "string" is still inside / / whereas substitution part is using different separator.

sed -n   "0,/string/ s|string|$x|p"   
I/am/a/ive/been/replaced

Upvotes: 1

Related Questions