tags:

views:

35

answers:

2

I have some lines stored in a text file called bashrc_snippet. I would like to insert them into .bashrc. Since I sometimes change the contents of the text file I would like to be able to re-insert them in the .bashrc-file. To do this I want to use marker lines:

# User things
HISTSIZE=1000

#START
alias ls='ls --color=tty'
... some more lines
#END

I would like a bash script to do this (possibly by using sed or awk). The algoritm should be:

  • If the marker lines are missing add them at the end of the file (and the lines of text)
  • If the marker lines are present, replace the contents between them with the new lines of text
A: 

Hello! I would like to suggest this (ex or vim commands):

ex -c '/^#START/+1,/^#END/-1 d' -c '/^#START/ r bashrc_snippet' -c 'wq'
Benoit
+1 for the answer to what he __wanted__, but the chosen answer should go to @hluk for providing what Lennart __needs__
Kimvais
I cannot agree more
Benoit
+1  A: 

don't really understand your requirement, but here's a guess

#!/bin/bash

rcfile="$1"
snippet="$2"
var=$(<"$snippet")
if grep -q "START" "$rcfile" ;then
   awk -v v="$var" '/START/ {
     print $0
     print v
     f=1
   }f &&!/END/{next}/END/{f=0}!f' "$rcfile" >t && mv t "$rcfile"
else
   echo "#START" >> "$rcfile"
   echo "$var" >> "$rcfile"
   echo "#END" >> "$rcfile"
fi

to use:

$  ./test.sh rc_file bashrc_snippet
ghostdog74
It looks promising. But there is a small bug: when marker does not exist it writes to the rcFile, but when the marker exist it writes to stdout.
Lennart Schedin
well, it really isn't too difficult to redirect and rename it. see edit. i/o redirection are really basic stuff in using the shell so you could have easily solved it yourself.
ghostdog74
Thanks! It works well!
Lennart Schedin