added command generation with foreach
refactored loop to use proper regex replacement