Grep to find the correct line, sed to change the contents, then putting it back into the original file?
Try:
sed -i.bak '/firmware_revision/ s/test/production/' myfile.py
Here, /firmware_revision/
acts as a condition. It is true for lines that match the regex firmware_revision
and false for other lines. If the condition is true, then the command which follows is executed. In this case, that command is a substitute command that replaces the first occurrence of test
with production
.
In other words, the command s/test/production/
is executed only on lines which match the regex firmware_revision
. All other lines pass through unchanged.
By default, sed sends its output to standard out. You, however, wanted to change the file in place. So, we added the -i
option. In particular, -i.bak
causes the file to be changed in place with a back-up copy saved with a .bak
extension.
If you have decided that the command works for you and you want to live dangerously and not create a backup, then, with GNU sed (Linux), use:
sed -i '/firmware_revision/ s/test/production/' myfile.py
By contrast, on BSD (OSX), the -i
option must have an argument. If you don't want to keep a backup, provide it with an empty argument. Thus, use:
sed -i '' '/firmware_revision/ s/test/production/' myfile.py
Edit
In the edit to the question, the OP asks for every occurrence of test
on the line to be replaced with production
. In that case, we add the g
option to the substitute command for a global (for that line) replacement:
sed -i.bak '/firmware_revision/ s/test/production/g' myfile.py
On older machines with old-school sed
that doesn't support option -i
:
TF=$( mktemp -t "${0##*/}"_$$_XXXXXXXX ) && \
trap 'rm -f "$TF"' EXIT HUP INT QUIT TERM && \
sed '/firmware_revision/ s/test/production/' myfile.py >"$TF" && \
mv -f "$TF" myfile.py