0

I have an html file and I want using bash, to insert a dollar sign before the curly brackets, so something like:

<h1>My name is {HOSTNAME}. <h1>

becomes:

<h1>My name is ${HOSTNAME}. <h1>

My code so far:

while read -r line; do
        new_index=$(echo ${line} | sed '/^{/s/^/\$/')  #the line to insert the $
        echo $new_index 
done < "web/index.html"  #the file I'm reading from

But it doesn't seem to work, why?

Edit: I'm using bash for exercising purposes only, not a real life application.

oguz ismail
  • 1
  • 16
  • 47
  • 69
  • 3
    [Don't Parse XML/HTML With Regex.](https://stackoverflow.com/a/1732454/3776858) I suggest to use an XML/HTML parser (xmlstarlet, xmllint ...). – Cyrus Apr 13 '20 at 06:32
  • I'm using bash exercising purposes only. – Somayyah Mohammed Apr 13 '20 at 06:34
  • Here if you want to shoot your self in the foot: `while read -r line; do echo "${line/'{HOSTNAME}'/'${HOSTNAME}'}"; done < file.html ` – Jetchisel Apr 13 '20 at 07:20
  • 1
    @Cyrus I don't know the full context, but this might actually be a case where parsing the HTML isn't necessary or even desirable; it may be that the substitution should be made independent of context -- in the HTML header and body, in tag attributes, possibly even in inline scripts (but probably not in CSS). If this is correct, it may be best to use tools that don't try to understand the HTML structure. – Gordon Davisson Apr 13 '20 at 07:30

1 Answers1

1

Use sed with the -i flag to edit the file in place.

sed -i 's/{/\${/g' index.html
Irfan434
  • 1,463
  • 14
  • 19
  • 2
    GNU sed works fine with this but note that you don't need to escape the dollar sign in the replacement, and actually should not escape it if portability matters because, as per the [POSIX standard](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html), the result is unspecified. – luciole75w Apr 13 '20 at 14:05
  • 2
    You probably don't want to add `$` if there is already one, so: `sed -i 's/\([^$]\){/\1${/g'` – Léa Gris Apr 13 '20 at 14:40