3

I'm trying to replace the following (in it's simplest form)

{filedir_9}file.jpg

with

{filedir_7}file.jpg

Using

sed -i -e 's/(\{filedir_9\})([a-z\-\_0-9]+).jpg/\{filedir_7\}$2$3/g'

But I'm getting : RE error: invalid repetition count(s)

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
wot
  • 192
  • 2
  • 14
  • 1
    Try `sed -i '' -e 's/{filedir_9}\([-a-z_0-9]\{2,\}\)\.jpg/{filedir_7}\1/g'`. Why do you want to use Group 3 placeholder if you tried to capture two subpatterns? Note that `\{` opens a limiting quantifier in a POSIX BRE pattern, you need `{` to match a literal `{`. To create a capturing group you need `\(...\)`, not `(...)` and inside the replacement, you should use `\1` to refer to Group 1 value. In POSIX patterns, escaped sequences inside bracket expressions are not supported, you should put `-` at the start/end of the pattern, escaping it does not work. – Wiktor Stribiżew Jun 06 '18 at 21:18
  • thank you, that helped get what i needed – wot Jun 07 '18 at 18:56
  • I posted an answer with some more explanations. – Wiktor Stribiżew Jun 07 '18 at 19:26

1 Answers1

5

You may use

sed -i '' -e 's/{filedir_9}\([-a-z_0-9]\{2,\}\)\.jpg/{filedir_7}\1/g'

Note that \{ opens a limiting quantifier in a POSIX BRE pattern, you need { to match a literal {.

To create a capturing group in a BRE POSIX pattern, you need \(...\), not (...) and inside the replacement, you should use \1 to refer to Group 1 value.

In POSIX patterns, escaped sequences inside bracket expressions are not supported, you should put - at the start/end of the pattern, escaping it does not work (the \ is treated as a literal \ char).

Also, to match a dot, you need to escape the . char in the pattern, if it is unescaped, it matches any char.

Inside the replacement string, you should use \1 rather than $1 (Perl-like placeholders). Note you are using placeholders to Group 2 and 3, while your (\{filedir_9\})([a-z\-\_0-9]+).jpg pattern only attempts to capture 2 substrings, and thus there is no Group 3 (so, no point using $3 or \3, it is empty).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Fantastic! One question, what is the second param, the '' ? – wot Jun 09 '18 at 12:35
  • @wot That is a placeholder for an empty backup. If you need to create a backup, replace `''` with `.bak`. See [sed command with -i option failing on Mac, but works on Linux](https://stackoverflow.com/questions/4247068). – Wiktor Stribiżew Jun 09 '18 at 17:07