# Replace second derivative with product rule

Suppose that after some calculations, I find

a[x]*D[g[x],x,x]+b[x]*D[h[x],x,x]+c[x]*D[j[x],x]


What sort of operations do I need to do in Mathematica such that the output becomes

-D[a[x],x]*D[g[x],x]-D[b[x],x]*D[h[x],x]+c[x]*D[j[x],x]


This corresponds to making the replacement \begin{align} a(x)\frac{d^2g}{dx^2}=\frac{d}{dx}\left(a(x)\frac{dg}{dx}\right)-\frac{da}{dx}\frac{dg}{dx} \end{align} and ignoring the $$\frac{d}{dx}\left(a(x)\frac{dg}{dx}\right)$$ term.

In general, $$g[x]$$ and $$h[x]$$ can be anything, with the only commonality being that they are twice differentiated. I'm thinking that the solution will involved Replace[] and Map[], but I'm not sure how to apply them.

I am interested in terms like \begin{align} \frac{a_1(x)^{n_1}a_2(x)^{n_2}\cdots}{a_3(x)^{m_1}a_4(x)^{m_2}\cdots}\frac{d^2g}{dx^2} \end{align} where $$a_1$$ or $$a_3$$ might be $$g(x)$$ itself. Then, the Mathematica code should perform the operation: \begin{align} \frac{a_1(x)^{n_1}a_2(x)^{n_2}\cdots}{a_3(x)^{m_1}a_4(x)^{m_2}\cdots}\frac{d^2g}{dx^2}\to-\frac{d}{dx}\left(\frac{a_1(x)^{n_1}a_2(x)^{n_2}\cdots}{a_3(x)^{m_1}a_4(x)^{m_2}\cdots}\right)\frac{dg}{dx} \end{align}

rule = Derivative[2][f_][x_] g__ :> -D[f@x, x] D[Times@g, x];

which seems to do what you want. The difficulty was the peculiar FullForm of the Derivative function as seen in rule.