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 
1
  • 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. Commented Nov 26, 2018 at 4:48

2 Answers 2

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.

0
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 
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.