1

How to use sed regex to replace to words related to each other and one character between them with out change the character and the two words as group like that

ahmed#mohamed 
ahmed$mohamed
ahmed7mohamed

I didn't want to replace ahmed only and then replace mohamed only

I used

sed -i 's/ahmed.mohamed/mohamed.ahmed/g'

but make all like this I want to keep the character between them.

mohamed.ahmed
mohamed.ahmed
mohamed.ahmed
  • Thanks for showing us the result that you got from the command that you tried, but you should also show the result that you want.  Your explanation of the result you wanted is pretty good, but not entirely clear. – Scott Nov 26 '18 at 4:48
1

You're very close. You need to use capturing parentheses:

sed -E -i 's/ahmed(.)mohamed/mohamed\1ahmed/g'

The \1 is replaced with the text of the first set of parentheses.

1

You want to swap the two strings ahmed and mohamed that are separated by some character.

The issue in your expression,

s/ahmed.mohamed/mohamed.ahmed/

is that the character in-between the words is always replaced by a dot. The solution is to capture the character and replace it with itself.

This is one way of doing so with sed, which also uses the same capturing mechanism to avoid typing in the two strings again for the replacement:

sed 's/\(ahmed\)\(.\)\(mohamed\)/\3\2\1/'

or,

sed -E 's/(ahmed)(.)(mohamed)/\3\2\1/'

Testing on the given data:

$ sed -E 's/(ahmed)(.)(mohamed)/\3\2\1/' <file
mohamed#ahmed
mohamed$ahmed
mohamed7ahmed

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.