Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I am a beginner programmer and I've got thousands of lines of code that need to be swapped. I've been working on it by hand for 3 days and I think I'm starting to go blind. ;-P I was wondering if there was any way that I can do this with a regular expression with the sed command or in emacs with regexp or even a shell script.
I want to take this...
mapping[ $variable1 ] = main::$variable2;
mapping[ $variable3 ] = main::$variable4;and make this...
mapping[ main::$variable2 ] = $variable1;
mapping[ main::$variable3 ] = $variable4;This would be much easier to do with a regular expression if all of the variables were the same name. Unfortunately thats not the case. I'm not asking for anyone to do my job for me, but perhaps someone could point me in the right direction as how to swap these variables in the same line, or if it can even be done automated at all.
Thanks in advance,
Justin

I can't help with putting it into a batch script or anything, but I'll give it a go. I know regular expressions in a perl context, and I think you've asked perl questions before so I think you've got it available.
You'll note that your example is inconsistent...variables 1 and 2 swap, but 3 and 4 don't...I'll assume this is a typo and they should be swapped.
Assuming a line of code, or all of the code is in a scalar $mycode, the following line would do it:
$mycode =~ s/mapping\[ (.+?) ] = (.+?);/mapping[ $2 ] = $1\;/gm;
Note that perl assigns the variables $1,$2,,,$n to the nth set of parenthesis in a regexp. This is what makes this possible. I don't know if this behavior is duplicated in batch scripts, emacs, or anything else.
Learn everything you ever wanted to know about perl regular expressions here. You'll find pertinent information in the "search and replace" section.
Finally, you have a history of not posting back and letting people know if what they suggested worked or not. Could you start doing this so I know if this stuff helps? Thanks.
Good luck,
-SN

Whoops didn't mean to escape the ; in that regexp.
$mycode =~ s/mapping\[ (.+?) ] = (.+?);/mapping[ $2 ] = $1;/gm;
-SN

THanks for your help SN. It worked perfectly. I appreciate your help. I will try to post back results more often.
Justin

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |