Today I Learned: 17/09/2021 - Large scale text replacement in a running Docker container
For reasons no else need be slightly horrified by, I found myself recently needing to recursively replace some text in source files in a running Docker container using an orchestration tool. This could be done manually by execing into the container and then running the necessary commands, but this approach is awkward via an automated tool like Rundeck.
I settled on a hideous but workable one line monstrosity:
docker exec CONTAINER_NAME /bin/bash -c 'grep -l -Z -r -o "TEXT-TO-REPLACE" /base-dir/ | xargs -0 sed -i "s|TEXT-TO-REPLACE|NEW-TEXT|g"';
Passing the command to /bin/bash with -c keeps the pipe as part of the command run inside the container. If the grep … | xargs … command was passed directly to docker exec the shell would treat the pipe as the end of the command and pipe the result of docker exec … grep … into xargs on the calling shell, not in the container.