You could use a sed script:
#!/bin/sed -f
: restart
/^development/ {
: loop
s/\(password:\).*/\1 new_password/
t stop
n
/^[ \t]/ b loop
i\ password: new_password
b restart
}
: stop
Here we have a sed script that will start the main block of commands when it finds a line that starts with "development". Before I explain what the commands do, I think it is a good idea to explain the labels. Labels are defined with the :
command, and they give name to certain locations in the script. We define 3 labels.
restart
is used to go back to the start of the script.
loop
is used to iterate through the lines inside a development
block.
stop
is used when we have performed the change to the password, and we go to the end of the script, which actually allows the script to restart on the next input line.
Inside the main block, we first try to apply the password change using an s
substitute command. If it works, the t
test command that follows performs a jump to the end of the script, allowing the execution to continue in case another development
block is found.
If the substitute command doesn't succeed, the t
command does nothing, and we continue with the n
next command. This commands loads the next input line into the patter space (ie. sed's working buffer). We then check to see if it starts with a space or a tab, and if it does we jump to the "loop" label, allowing us to see if this new line is a line that contains the password field.
If it doesn't start with a white space character, we've reached the end of the block. The i
insert command is optional, but with it we can add the password line at the end of the block when it isn't found.
Finally, since we reached the end of the block, we must restart execution. We could just let execution read the end of the script, but since we've loaded a new line that doesn't start with a white space character, we must manually jump to the start to prevent sed from loading another line before restarting.
You can then run this script (suppose it's called chg_passwd.sed
) with:
./chg_passwd.sed database.yml
Hope this helps =)