The problem is simple: update a specific line in a specific section of a
.ini
file in a shell script. The file (a configuration file for Gitosis)
looks something like this:
[gitosis]
[repo repo1]
description = This is a repository with stuff in it
owner = A User
[repo repo2]
description = Another repository with stuff in it
owner = Another User
[repo docs]
description = Documentation
owner = A Manager
[group developers]
writable = repo1 repo2 docs
members = auser anotheruser
[group managers]
writable = docs
readonly = repo1
The goal is to append a value to the writable
line in the group developers
section (leaving the rest of the lines alone). Any solution will need to do
the following:
- find the
group developers
section; then - find the
writable
line in that section, if any, and update it.
This is simple to do in AWK:
- a rule sets a flag when you enter the
group developers
section; - another updates the
writable
line when the flag is set; - a thirds rule clears the flag when you leave the section;
- a final rule outputs other lines unchanged (we use a flag to skip the lines modified and output above).
Here’s the code:
# Clear the flag
BEGIN {
= 0;
processing }
# Entering the section, set the flag
/^\[group developers/ {
= 1;
processing }
# Modify the line, if the flag is set
/^writable = / {
if (processing) {
print $0" foo";
= 1;
skip }
}
# Clear the section flag (as we're in a new section)
/^\[$/ {
= 0;
processing }
# Output a line (that we didn't output above)
/.*/ {
if (skip)
= 0;
skip else
print $0;
}
Easy!