问题
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