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