4

I have 14-character line containing digits. How do I insert a char into it at the specific location, i.e. at 4th? So, if I have string like this: xxxxxxxxxxxxxx how do I change it to something like this: xxxx-xx-xxxxxxxx ? (x = digit)

Thanks! irek

irek
  • 1,075
  • 2
  • 11
  • 9

2 Answers2

6

If your lines only contain your digits, you can group the first four characters in a group:

\(....\)

and the following two ones in another group:

\(....\)\(..\)

Then, you just replace it by a backreference to the first group (\1), a dash, a backreference to the second group (\2) and another dash:

\1-\2-

The result:

$ echo 12345678900000 | sed 's/\(....\)\(..\)/\1-\2-/'
1234-56-78900000
brandizzi
  • 26,083
  • 8
  • 103
  • 158
2

Thanks brandizzi for your answer it helped me to get my one to work using a slightly different method

sed 's/^\(.\{4\}\)\(.\{2\}\)/\1-\2-/' 

the 4 and 2 work to replace the 4th character and then 2nd after that with dashes.

So xxxxxxxx becomes xxxx-xx-xx

D.A. Reyn
  • 81
  • 1
  • 2