Syntax error using sed for a find and replace

Viewed 52

I am trying to do a find and replace using sed. I am trying to find that : purge: [], to replace by purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"], but it does not work, here is my commande :

sed -i -e 's/purge: [],/purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],/g' myfile.txt

Could you help me please ?

Thank you very much !

2 Answers

You need to:

  • Change delimiters to a char other than a /, like ~ or !, or escape / delimiter chars inside the pattern (I'd suggest the former)
  • Escape the [ char in the pattern.

You can use

sed -i 's!purge: \[],!purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],!g' myfile.txt

See the online demo:

#!/bin/bash
s='Blah..purge: [], blah...'
sed 's!purge: \[],!purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],!g'<<< "$s"
# => Blah..purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"], blah...

Using sed

$ sed '/purge:/s|\(\[\)\(\]\)|\1"./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"\2|' myfile.txt
purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
Related