How do I prepend multiple lines from a variable to the beginning of a file?

0
0
Asked By CreativeTiger42 On

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

Answered By GawkGuru88 On

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!

Answered By QuirkySeagull66 On

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.

Answered By FileMaster99 On

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!

Answered By PrependerPro On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.