tags:

views:

60

answers:

2
sed 's/\([ab]\)\([ab]\)./\2\1x/g' file.txt

My understanding is: in file.txt, find any string start with either 'a' or 'b', followed by either an 'a' or a 'b', followed by any ONE char (say 'abc'), and replace it with the string 1st, and 2nd char switched palce, and 3rd char is x ('bax'). Is the syntax of the command correct? and am I correct?

+2  A: 

Yep, you are - note that the 'g' on the end means it'll make the substitution as many times as it can on every line. Any reason you couldn't just try it and see?

Jefromi
+3  A: 

You are correct, except for the start part. This will match characters anywhere in the string, as many times as possible, so you end up with substitutions like this:

"123ab1" to "123bax"
"1234ab" to "1234ab"
"ab1ba2" to "baxabx"
"bbaabb" to "bbxbax"

What you may want to do is anchor it to the start of the string with the caret character, like this:

s/^\([ab]\)\([ab]\)./\2\1x/g

Giving:

"abc123" to "bax123"
"123abc" to "123abc"
grkvlt
+1 I managed to miss where derrdji said 'start'. Good call.
Jefromi