Extended version of @YvesDaoust answer:
Given the parametric line:
L(t) = A + t D
Where D is a unit vector i.e. D • D = 1
The distance of a point P to a line L is:
t = D • (P - A)
The closest point P to a set of lines, in the least squares sense, is minimizing the Sum of errors E:
E = (P - L(t))^2
E = (P - (A + tD))^2
E = (P - A - tD)^2
E = (P - A - (D • (P - A))D)^2
E = (P - A - (D•P - D•A)D)^2
E = (P - A - (D•P)D + (D•A)D)^2
E = (P - (D•P)D - A + (D•A)D)^2
E = (P - (D D^T)P - A + (D•A)D)^2
E = ((I - (D D^T)) P - A + (D•A)D)^2
E = (C x - b)^2
Where
C = I - (D D^T)
x = P
b = A - (D•A)D
Where "I" is the 3x3 identity matrix. The least squares solution is:
C^T C x = C^T b
Other way to derive the same system is taking the derivative of equation:
E = (P - A - tD)^2
E = P•P - 2 P•A - 2t P•D + A•A + 2t A•D + t^2
Taking the derivative with respect to P and simplifying we get (remember to apply the chain rule when taking the derivative of "t" since it is a function of P):
dE/dP = 2(P - A - ((P - A) • D) D)
Equating this to zero:
dE/dP = 0
2(P - A - ((P - A)•D) D) = 0
P - ((P - A)•D) D = A
P - (P•D) D + (A•D) D = A
P - (P•D) D = A - (A•D) D
P - (D D^T) P = A - (A•D) D
(I - D D^T) P = A - (A•D) D
Where "I" is the 3x3 identity matrix. That is again a linear system of the form C x = b.
Remember that you still need to apply the summation to both sides of the equation, so it really is:
Sum(C^T C) x = Sum(C^T b)
So finally:
x = Sum(C^T C)^-1 Sum(C^T b)