One (Illustrator) method...
With the art you have...
- Select all
- Grab the Shape Builder Tool
- Hold Down the Option/Alt key and click-drag across the lines outside the rectangle to remove them
(After question edit) -- This will work for all your shapes. Just select all and then Option-Click-Drag with Shape Builder to remove what you don't want.
Another (Illustrator) method....
Move (or copy) the rectangle so it is on top of the paths.
Select the lines and this top rectangle.
Click the Divide button on the Pathfinder Panel (Window > Pathfinder)
Simply delete what you don't want.