sed replacing a string in a file

Simple example of replacement of a password field in /etc/shadow.

usern=robbie
encpass= :$1$CQoPk7Zh$370xDLmeGD9m4aF/ciIlC
sed -i "s/^${usern}\:[^\:]\{1,100\}\:/${usern}\:${encpass}\:/" /etc/shadow

Probably some more improvements here (e.g. determine maximum hashed password string length rather than "up to 100"), but it works for now.

Use case: orchestration of new system deployments - if I wish to roll out a pre-determined password.

  • There are plenty of other build/orchestration tools which also achieve this, but sometimes you need a quick/simple hack to get by in the short term.