I'm trying to modify a file named `index.html` that has a placeholder `{{INSERT_HERE}}`. I want to replace that placeholder with the contents from another file called `foo.txt`. The current content in `index.html` looks like this:
stuff
{{INSERT_HERE}}
more stuff
And `foo.txt` contains:
some html
some more html
After the operation, I want `index.html` to look like:
stuff
some html
some more html
more stuff
I've tried using `sed` and `perl` as shown in the resources I found, but they either overwrite the file or don't work as expected. Here's what I've tried:
```bash
#! /bin/bash
# sed -e "/{{INSERT_HERE}}/{r foo.txt" -e "d}" index.html
perl -pe 's/{{INSERT_HERE}}/`cat foo.txt`/e' index.html > index.html
```
What changes should I make to achieve the desired outcome? I prefer using `sed` if possible, but I'm open to other suggestions if needed.
3 Answers
Just a heads up, if you need a straightforward command, here's another way to do it:
```bash
sed '/{{INSERT_HERE}}/r foo.txt' index.html | sed '/{{INSERT_HERE}}/d' > newfile.html
```
This reads the content of `foo.txt` into the output right where the placeholder is and then deletes the placeholder immediately after. It might be less direct but it definitely keeps your original file intact until you're ready to replace it.
To stick with `sed`, you're correct that it doesn't like overwriting the input file directly. Instead of outputting to the same file, consider these steps:
1. Run the `sed` command as suggested above to create a new file.
2. Check `index2.html` to see if it looks correct.
3. If it does, you can replace the original with this new file:
```
mv index2.html index.html
```
That way, you won't lose your data if something goes wrong!
It sounds like you're on the right track! The issue with your current `sed` command might be due to trying to read and write to the same file at the same time. Instead, try redirecting the output to a different file first, like this:
```
sed -e "/{{INSERT_HERE}}/{r foo.txt" -e "d}" index2.html
```
This will read from `index.html`, replace the line, and write the result to `index2.html`. If that works, you can then rename `index2.html` to `index.html` if you want to keep the original name. Using `tee` can also help you modify the existing file, but make sure you are cautious about overwriting it directly!
I tried that command, and it still didn't work for me. It wiped my `index.html` clean! Be careful with these commands!