开发者

sed inserting dash into string

开发者 https://www.devze.com 2023-03-24 22:28 出处:网络
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:开发者_如何学JAVA xxxxxxxxxxxxxx how do I change it to

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:开发者_如何学JAVA xxxxxxxxxxxxxx how do I change it to something like this: xxxx-xx-xxxxxxxx ? (x = digit)

Thanks! irek


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号