Print XYZ of nearest Villager (or other entity)

Solution 1:

In general, the below command will display the coordinates of all entities of a certain type:

/execute as <relevant entities> run data get entity @s Pos

For your specific cases:

/execute as @e[type=villager,distance=0..40] run data get entity @s Pos

will display the coordinates for all villagers within 40 blocks. To display only the coordinates of the nearest villager:

/data get entity @e[type=villager,sort=nearest,limit=1] Pos

(the /execute is not necessary when you are only dealing with one entity)