0

In my code file I have several lines asT V= X T(A); And I want the text after = to be replaced as X(T,A) with some help I got this pattern s/X\s+([^\(]*)\(/X(\1,/g; for find and replace it works great but the problem is when we have no args to pass for T Ex.T V= X T(); then after replacement it will be like X(T,) (see the extra comma) I knew it's because of /X(\1, can somebody help me rid of that extra comma, Sadly I am no regex guy.

Is there any sort of conditional we could have to say if the () is empty then do X(\1/g rather than /X(\1,/g

  • Use two s: sed -E 's/X\s+([^\(]*)\(\)/X(\1)/g;s/X\s+([^\(]*)\(/X(\1,/g' the 1st one will only replace the T() stuff, the 2nd one will replace the rest (as the T() was already changed and no longer matches the regex) – don_crissti Jan 30 '17 at 19:38
1

Something like this ought to do it, if you run it on the file(s) after having run the first substitution that introduces the error:

sed 's/X(\([^,]*\),)/X(\1)/g'

It will substitute X(<something-not-a-comma>,) with X(<something-not-a-comma>).

To do both substitutions in one go:

sed -e 'the first substitution' -e 'the second substitution'
  • it works for sure ,but I really wanna avoid second run – RaGa__M Jan 30 '17 at 19:26
  • @FallingFromBed you know you can run both substitution in one pass ? – Archemar Jan 30 '17 at 19:38
  • @FallingFromBed Updated. I thought that you now had files with the error in them. – Kusalananda Jan 30 '17 at 19:39
  • sed -e s/X\s+([^(]*)(/X(\1,/g -e 's/X(([^,]*),)/X(\1)/g' error -bash: syntax error near unexpected token `(' – RaGa__M Jan 30 '17 at 19:49
  • @FallingFromBed You need to single-quote the first expression too. – Kusalananda Jan 30 '17 at 19:50
1

@Kusalananda Looks like he is using Extended regex without -E option in his first substitution command in

sed -e 's/X\s+([^\(]*)\(/X(\1,/g' -e 's/X(\([^,]*\),)/X(\1)/g' ./file

But the second command looks fine. Making everything in extended Regex, this will work

sed -Ee 's/X\s+([^\(]*)\(/X(\1,/g;s/X\(([^,]*),\)/X(\1)/g' ./file
  • @FallingFromBed See this for your query about -E option stackoverflow.com/questions/3139126/… – boobalan Jan 30 '17 at 20:16
  • No, I'm not using ERE in my substitution. – Kusalananda Jan 30 '17 at 20:17
  • Of course,You didn't. So i changed your command into Extended regex form as well. Verify if its correct. – boobalan Jan 30 '17 at 20:18
  • what the -r is for? – RaGa__M Jan 30 '17 at 20:18
  • does sed -Ee 's/X\s+([^\(]*)\(/X(\1,/g' -Ee 's/X\(([^,]*),\)/X(\1)/g' works? – RaGa__M Jan 30 '17 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.