I'm trying to prepend multiple lines from a variable, which I gathered using a grep command, to the beginning of a file. My current script is having issues, especially with the multiline text not working well with sed. Here's my script:
#!/bin/bash
END="${1}"
FILE="${2}"
OUTPUT="${3}"
TODAY="[$(date +%d-%m-%Y" "%H:%M:%S)]"
DIFFERENCE=$TODAY$(git diff HEAD HEAD~$END $FILE | grep "-[-]" | sed -r 's/[-]+//g')
sed -i '' -e '1i '$DIFFERENCE $OUTPUT
Can anyone help me figure out how to correctly append these lines at the start of my file?
4 Answers
You can tackle this using **gawk** (GNU awk) easily. Here’s a command that could work for you:
```bash
gawk -i inplace -v "txt=$DIFFERENCE" 'BEGINFILE{print txt}{print}' $OUTPUT
```
This does a nice job of prepending variable content to your file. The `-v` option makes your variable available to the gawk script, and `BEGINFILE` ensures that it prints before the first line of the file. Give it a shot!
While it might be a bit rough, you can read the entire file into a variable first. Here’s a way to do that:
```bash
variable=$( $newfile
# Now append your variable to the new file
echo "${DIFFERENCE}n$variable" > $newfile
```
This method lets you manipulate the contents before writing them back to the file.
Just remember, if you're redirecting output to the same file you're reading from, it can cause problems. I would suggest using `tee` or even a temporary file for safety, like so:
```bash
echo -e "$DIFFERENCE
$(cat $OUTPUT)" | tee $OUTPUT.tmp
mv $OUTPUT.tmp $OUTPUT
```
That way you avoid modifying a file while you're still reading from it. It's a good way to keep things safe!
If you want something simpler and are okay with creating a temporary file, you could do this:
```bash
# Create your prepending content
P="[$(date +%d-%m-%Y" "%H:%M:%S)]n"
C="$(cat $OUTPUT)"
echo -e "$P$C" > $OUTPUT
```
This way you can easily join them together and write back to the file.
Related Questions
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String