How can I use sed to replace multiple characters?

7,061

Your command would have worked if you had escaped the curly braces (I've also quoted the $1 that you leave unquoted for unknown reasons):

$ set -- 3
$ echo 12345 | sed "s/^\(.\{$1\}\)/\1hi/"
123hi45

The repetition modifier {n} is an extended regular expression modifier, which in a basic regular expression is written as \{n\}. The sed utility is using basic regular expressions by default.

You would save a few characters by rewriting it as

echo 12345 | sed "s/^.\{$1\}/&hi/"

Personally I would have taken another approach...


You want to add the string hi after the 3rd character in 12345 where "the 3rd" is given by the value in $1.

echo 12345 | sed 's/./&hi/'"$1"

When $1 is 3, then the sed expression would look like

s/./&hi/3

This would replace the 3rd match of . (any character) with that same character (this is what & does in the replacement) followed by hi.

Putting a digit, n, at the end of an s command in sed like this makes sed substitute the n:th match of the pattern.

Test running (with a modified input and replacement for readability reasons):

$ set -- 3
$ echo abcde | sed 's/./&<hi>/'"$1"
abc<hi>de
$ set -- 4
$ echo abcde | sed 's/./&<hi>/'"$1"
abcd<hi>e
$ set -- 1
$ echo abcde | sed 's/./&<hi>/'"$1"
a<hi>bcde
Share:
7,061

Related videos on Youtube

Jeff Schaller
Author by

Jeff Schaller

Unix Systems administrator http://www.catb.org/esr/faqs/smart-questions.html http://unix.stackexchange.com/help/how-to-ask http://sscce.org/ http://stackoverflow.com/help/mcve

Updated on September 18, 2022

Comments

  • Jeff Schaller
    Jeff Schaller over 1 year

    I have this script:

    replace 3
    
    echo 12345 | sed "s/^\(.\){"$1"}/\1hi/"
    

    I also tried this:

    echo 12345 | sed "s/^\(.{"$1"}\)/\1hi/"
    

    In this situation I want the script to add 'hi' after the first 3 characters of '12345' (123hi45). This is a script so the '3' is an argument and can change. I'm really stuck here. Thanks in advance!

  • Stéphane Chazelas
    Stéphane Chazelas over 4 years
    \{n,m\} was added to BRE before {n,m} was added to ERE. As it broke backward compatibility for ERE, there are some egrep or awk implementations that still don't support it.