2

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

  • Do you have to do this logic inside sed, or could your script detect the value of $ANCHOR and use a suitable replacement? – Jeff Schaller May 26 at 13:35
  • I prefer to use SED so I do not modify how things are at all. It would be awesome if there was a way as I am currently creating a new function just to implement new logic to handle this. If it were possible, all I have to do is just a replacement from '' to 'some value' inside anchor and I am done. – conanDrum May 26 at 13:47
  • Doesn't the SED regex have a match for EOF? – conanDrum May 26 at 13:50
  • of course It could be possible to use another method alltogether. maybe there is a way to do this with another command that DOES facilitate regex matching AND EOF matching within the regex area? – conanDrum May 26 at 13:59
  • “I prefer to use SED so I do not modify how things are at all.“ — you have to change something: You will have to change the script that calls sed, and adding a bit of logic to this script may be easier. – ctrl-alt-delor May 26 at 14:39
1
[[ -z $ANCHOR ]] && ANCHOR='$' || ANCHOR="/$ANCHOR/"
sed -i "${ANCHOR}i \\$PARAMVALSEDINS" "$FILEPATH"
0
$ 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.