Ryan
Ryan

Reputation: 1221

Regex find and replace with characters that can vary

I'm trying to write a line in a bash script that takes all instances of pushing and popping a register and changes it from the 32-bit register to the 64-bit register. For example, push ecx Should become push rcx

The only character that can vary is the second to last one, so finding with e\wx works fine, but how do I make it so that whatever character is found in \w is kept, as well as whichever, of the push/pop is present? The only character that needs to change is the e to an r.

In short, I have this:

 sed -i -e "s/push eax/push rax/"
 sed -i -e "s/push ebx/push rbx/"
 sed -i -e "s/push ecx/push rcx/"
 sed -i -i "s/push edx/push rdx/"
 sed -i -e "s/pop eax/pop rax/"
 sed -i -e "s/pop ebx/pop rbx/"
 sed -i -e "s/pop ecx/pop rcx/"
 sed -i -i "s/pop edx/pop rdx/"

And I want to know if I can do it in one line

Thanks in advance!

Upvotes: 0

Views: 55

Answers (2)

Aaron
Aaron

Reputation: 24812

Here you go :

sed -i 's/\(push\|pop\) r\([abcd]\)x/\1 e\2x/'

Sample run :

$ echo """push rax
push rbx
push rcx
push rdx
pop rax
pop rbx
pop rcx
pop rdx
nop""" | sed 's/\(push\|pop\) r\([abcd]\)x/\1 e\2x/'
push eax
push ebx
push ecx
push edx
pop eax
pop ebx
pop ecx
pop edx
nop

Upvotes: 2

Code Different
Code Different

Reputation: 93161

Use a capture group:

sed -i -e "s/(push|pop) e(\w+)/\\1 r\\2/"

I don't have a console handy so I can't test it, you can see the Regex stub here.

Upvotes: 2

Related Questions