0

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!

0

2 Answers 2

4

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
1
  • \{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. Dec 14, 2019 at 20:21
0

The following works for me:

#!/bin/sh

n=$1

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

This requires the use of the -r option for sed to specify extended regex (-E on macos). I'm not sure how your input is going to be fed into the script though (12345) so I just left it as you had in your example.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .