Poor man large linear encoder
I'm not sure of the mechanics of what you describe but if it slides on a specific legth bar you can use an optical sensor that reads either slots on the bar or reflective areas (like a shiny sticker every 2cm)



Another idea is the use of a small wheel that has a similar optical sensor and by reading the wheel movement you can calculate the distance.