Search code examples
regexsedswap

Swap 2nd and 6th char in a string using sed command


I wrote a sed command to swap the second and sixth character in the numbers below.

I am getting the following error:

sed: file minor1.sed line 4: invalid reference \9 on `s' command's RHS

My sed command (script.sed):

s/\(.\){10}/\1\6\3\4\5\2\7\8\9\10/g

I am using sed -r -f script.sed Input.txt to run the command.

Input.txt -

8668797647
8884747424
3716706006
8662665588

Can anyone help me figure out why I am getting this error?


Solution

  • Not sure why you're only getting that error at \9, but here's an expression that does do what you're after, if you save it as a .sed and run it as you suggest:

    s/(.)(.)(.{3})(.)/\1\4\3\2/
    

    It does not have the g at the end, because you only want to replace the first match on each line anyway.

    It matches: one character, one character, three characters and one character and then writes them back as the first match, the fourth match (sixth character), the third match (characters in between) and the second character. Effectively swapping the 2nd and 6th.