Insert a character at a specific location using sed
How to insert a dash into a string af开发者_运维百科ter 4 characters using sed (e.g., 201107
to 2011-07
)?
echo "201107" | sed 's/201107/2011-07/'
Should work. But just kidding, here's the more general solution:
echo "201107" | sed -r 's/(.{4})/\1-/'
This will insert a -
after every four characters.
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
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.
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/'
精彩评论