Skip to content

Instantly share code, notes, and snippets.

@WarFox
Last active January 26, 2022 12:19
Show Gist options
  • Save WarFox/32582c07271dcf6e96827af336355247 to your computer and use it in GitHub Desktop.
Save WarFox/32582c07271dcf6e96827af336355247 to your computer and use it in GitHub Desktop.
Replace section in a file
#!/usr/bin/env bash
file_with_anchor_text=$1
file_with_new_content=$2
BEGIN_TEXT='<!-- BEGIN anchor text --!>'
END_TEXT='<!-- END anchor text --!>'
function get_line_number() {
local text=$1
echo $(grep -n "$text" $file_with_anchor_text | sed 's/\(.*\):.*/\1/g')
}
BEGIN_LINE=$(get_line_number "$BEGIN_TEXT")
END_LINE=$(get_line_number "$END_TEXT")
## Get the head and tail from $file_with_anchor_text and put the content form $file_with_new_content in between head and tail
cat <(head -n $(expr $BEGIN_LINE + 1) $file_with_anchor_text) $file_with_new_content <(tail -n +$(expr $END_LINE - 1) $file_with_anchor_text) >temp
mv temp $file_with_anchor_text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment