1

I have to replace a string present between two strings using sed command in Unix.

My Input is :

Apple'Mangoabcd'Orange'Mangoxyz'Lemon'

The command I used is

sed 's/Mango.*'"'"'/+XXXX'"'"'/'

My desired Output is

Apple'XXXX'Orange'XXXX'Lemon'

The output I get is

Apple'XXXX'

I want to replace 'Mango+freetext' with 'XXXX' in all the places.

Sathya
  • 13
  • 3

1 Answers1

0
  1. If you just want to replace Mango and you know it is Mango, then you just do

    sed 's/Mango/XXXX/g'
    
  2. If you want to replace Mango<freetext> where the freetext does not contain a single quote ', then you do :

    sed "s/'Mango[^']*/'XXXX/g"
    

    we added the extra quote before Mango to make sure we exclude strings such as 'SquashedMangoJuice'

  3. If you want to replace the string between the words Apple and Orange, then you have to do it a bit different :

    sed "s/Apple'[^']*'Orange/Apple'XXXX'Orange/g" 
    

    or using back-references

    sed "s/\(Apple'\)[^']*\('Orange\)/\1XXXX\2/g"
    

The reason why your original command is failing is that sed is greedy. What I mean is that the combination .*' will pick everything until the last quote. That is, it will represent Mango'Orange'. The culprit is the last quote after Orange. Above, we fixed this by replacing your . with [^']. This means all characters except the quote '.

kvantour
  • 25,269
  • 4
  • 47
  • 72
  • Sorry. I missed few things. I have to replace free texts present between 'Mango' and first instance of ' . So, My input will be some thing like this "Input = Apple'Mangoabcd'Orange' – Sathya Jun 20 '18 at 12:23
  • @Sathya, could you please update your original question to represent this. Especially the given input and expected output. Also clearly state if the Apples and Oranges have anything to do with the replacement (if it is a condition or not) or if `Pear'Mango_foobar'Banana'` should also be replaced. Also could the string that need to be replaced contain a quote. – kvantour Jun 20 '18 at 12:28
  • I have edited my question. I have multiple occurrence of the string which I am replacing in my Input. – Sathya Jun 20 '18 at 12:33
  • Hi, I tried the 2nd option. but it is replacing only the first instance. so my output is coming as " Apple'XXXX'Orange'Mangoabcd'Lemon' " instead of " Apple'XXXX'Orange'XXXX'Lemon' " – Sathya Jun 20 '18 at 12:47
  • Thank you so much for your help. 2nd Command perfectly suits my requirement :-) – Sathya Jun 21 '18 at 09:37
  • @Sathya you are welcome. Don't forget [someone answers](https://stackoverflow.com/help/someone-answers) – kvantour Jun 21 '18 at 09:40