Insert a character at a specific location using sed

旧城冷巷雨未停 提交于 2020-08-22 04:06:14

问题


How to insert a dash into a string using sed (e.g., 201107 to 2011-07)?


回答1:


echo "201107" | sed 's/201107/2011-07/'

Should work. But just kidding, here's the more general solution:

echo "201107" | sed 's/^\(.\{4\}\)/\1-/' 

This will insert a - after the first four characters.

HTH




回答2:


For uncertain sed version (at least my GNU sed 4.2.2), you could just do:

echo "201107" | sed 's/./&-/4'

/4 -> replace for the 4th occurrence (of search pattern .)

& -> back reference to the whole match

I learned this from another post: https://unix.stackexchange.com/questions/259718/sed-insert-character-at-specific-positions




回答3:


The following will match perform the replacement only on strings of four digits, followed by strings of two digits.

$ echo '201107' | sed 's/\([0-9]\{4\}\)\([0-9]\{2\}\)/\1-\2/'
2011-07

Sed regex is a little awkward, because of the lack of \d, and the need to escape parenthesis and braces (but not brakets). My solution ought to be 's/(\d{4})(\d{2})/\1-\2/' if not for these peculiarities.




回答4:


I know this is diggin up a massive dinosaur, but if you wanted to eliminate the 6 tailing zeros

echo '20110715000000' | sed 's/\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{6\}\)/\1-\2-\3/'


来源:https://stackoverflow.com/questions/6845069/insert-a-character-at-a-specific-location-using-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!