Ashish Gaur
Ashish Gaur

Reputation: 2050

Replace string recursively using sed

I have a file with below string :

||||||

I want to replace every occurrence of || with |""| so I used

sed 's/||/|\"\"|/g' temp2.csv

but I got the output as :

|""||""||""| instead of |""|""|""|""|""|

I found that sed is not doing the replacement recursively, how can i make sed to do the replacement recursively so it moves over to the next line only when the previous line have no occurrences of ||

Thanks for your help.

Upvotes: 2

Views: 355

Answers (3)

Jotne
Jotne

Reputation: 41456

Using awk you can do this:

#echo '||||||' | awk '{gsub(/\|\|/,"|\"\"|")}1'
|""||""||""|

Upvotes: -2

Kent
Kent

Reputation: 195109

the most straight forward way would be call the sed substitution twice. but I think this sed one-liner may be better, because it works if you say, I want to recursively replace |||..{n}..| into |""|""|...{n}..|""|

sed ':a s/||/|""|/g; t a' file

test with your data:

kent$  cat f
||||||

kent$  sed ':a s/||/|""|/g; t a' f
|""|""|""|""|""|

Upvotes: 5

SheetJS
SheetJS

Reputation: 22905

sed does not support lookahead or lookbehind, but in your case you can just make a second pass:

<temp2.csv sed 's/||/|\"\"|/g' | sed 's/||/|\"\"|/g'

Upvotes: 2

Related Questions