Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a character at a specific location using sed

Tags:

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

like image 985
irek Avatar asked Jul 27 '11 13:07

irek


People also ask

How do you pass special characters in sed?

\ 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.

How do you use sed on a specific line?

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.


2 Answers

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

like image 50
Zsolt Botykai Avatar answered Oct 19 '22 00:10

Zsolt Botykai


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

like image 22
Johnny Wong Avatar answered Oct 19 '22 01:10

Johnny Wong