How to insert a dash into a string after 4 characters using sed (e.g., 201107
to 2011-07
)?
\ followed by a letter has a special meaning (special characters) in some implementations, and \ followed by some other character means \c or c depending on the implementation. With single quotes around the argument ( sed 's/…/…/' ), use '\'' to put a single quote in the replacement text.
Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With