I use the following to successfully find my ANCHOR (regex pattern) and replace it with my param-value inside a file (filepath).
sed -i $"/$ANCHOR/i \\$PARAMVALSEDINS" "$FILEPATH"
What I need is for when my ANCHOR is '' (empty) to instead match my EOF and do the replacement there.
So I imagine doing something like this:
if ANCHOR='' then ANCHOR='$EOF' so that SED successfully finds the EOF and proceeds with the replacement.
Can this be done? Couldn't find anything specific except for this:
sed -i -e "\$aPARAMVALSEDINS" "$FILEPATH"
However, this does not involve the ANCHOR variable and I will implement it if my question is not possible to be answered.
PS. Of course it could be possible to use another method altogether. Maybe there is a way to do this with another command that DOES facilitate regex matching AND EOF matching within the regex area? e.g. another -i $"/$ANCHOR/i \$PARAMVALSEDINS" "$FILEPATH" where if $ANCHOR can be a match for EOF
Thanks
2 Answers 2
[[ -z $ANCHOR ]] && ANCHOR='$' || ANCHOR="/$ANCHOR/"
sed -i "${ANCHOR}i \\$PARAMVALSEDINS" "$FILEPATH"
$ ANCHOR=${ANCHOR:+"/$(printf '%s\n' "$ANCHOR" | sed -e 's:[][\/.^$*]:\\&:g')/"}
$ sed -i -e "${ANCHOR:-\$}i \\$PARAMVALSEDINS" "$FILEPATH"
As a first step, escape the contents of anchor variable to make it robust to be used as an expression in sed matching brackets.
In the next step, if we find the anchor var empty, we use a literal $ symbol in it's place which then gets interpreted as EOF by sed.
HTH.
Note : make sure paramvalsedins var is similarly escaped before it's use.
sed
, and adding a bit of logic to this script may be easier.