Passing a varaible to sed issue

I am unable to make it work. I tried dbl quotes ...etc. Nothing works. I am trying to replace value in an XML file to current system date/time. Here is my code:

NTIMESTAMP=`date '+%m%d%Y%H%M%S'`
 sed -e 's|<TIMESTAMP>[0-9a-z.]\{1,\}|<TIMESTAMP>$NTIMESTAMP|g' $QLOG
  
 Input data sample:
 <MSGTYPE>QI</MSGTYPE><TIMESTAMP>06062017120000</TIMESTAMP>
  
 Output with my code "Not working":
 <MSGTYPE>QI</MSGTYPE><TIMESTAMP>$NTIMESTAMP</TIMESTAMP>

What am I doing wrong? I tried using double quotes, when I do it blanks out the timestamp !

Please help. Thanks

---------- Post updated at 11:26 AM ---------- Previous update was at 11:16 AM ----------

I think I found the solution. Using this works perfectly:

eval "$(echo "sed -e 's|<TIMESTAMP>[0-9a-z.]\{1,\}|<TIMESTAMP>$NTIMESTAMP|g' $QLOG")"

You say you tried double quotes, but see:

sed -e "s|<TIMESTAMP>[0-9a-z.]\{1,\}|<TIMESTAMP>$NTIMESTAMP|g" file
 <MSGTYPE>QI</MSGTYPE><TIMESTAMP>06092017182948</TIMESTAMP>

I tried that and did no work at all. But using this works:

eval "$(echo "sed -e 's|<TIMESTAMP>[0-9a-z.]\{1,\}|<TIMESTAMP>$N_TIMESTAMP|g' $QLOG")" > $QLOG.tmp

It seems to be the only way to make it work afterall. Thanks

In what way did it "not work"? What did it actually do?

Whenever arguments start being finicky, its a good idea to print them back out to make sure you're putting in what you think you are. Try

printf "%s\n" "s|<TIMESTAMP>[0-9a-z.]\{1,\}|<TIMESTAMP>$NTIMESTAMP|g"

to make sure its doing what you think it is.

eval is definitely not "the way" to do this. That it's not working suggests to me the input might have things in it which are unexpected and eval works around by quote-splitting or some such.

When I use SED with double " to take $NTIMESTAMP value, it gives me this:

 <MSGTYPE>QI</MSGTYPE><TIMESTAMP>$NTIMESTAMP</TIMESTAMP>
 

It is not passing the date value from the variable.

Only when I use eval, it works fine.

I ran your printf and I get this:

s|<TIMESTAMP>[0-9a-z.]\{1,\}|<TIMESTAMP>06092017131913|g

Good, and if printf doesn't mess it up, neither will sed. The shell does not differentiate between the two, substitution happens before sed or printf is run.

Hit the up arrow on your console to repeat the 'printf' command, delete the 'printf "%s\n"', insert 'sed' in its place, go to the end, add '< inputfile > outputfile' and hit enter.

If that doesn't work, show exactly what you do and exactly what result you get, word for word, letter for letter, keystroke for keystroke. You're doing some substitution or escaping somewhere which causes $ to be taken literally. Notably, you can't store $ in a variable and expect it to be evaluated later.