Shell scripting challenge
I'm trying to write a shell script in Bash that will remove an entire section in a text file if that section exists.
Here's an example of a file that needs to be modified:
Code:
[Section1]
PropA=123
PropB=456
PropC=789
[Section2]
PropA=xxx
PropB=yyy
PropC=zzz
[Section3]
PropA=000
PropB=111
PropC=222
The shell script needs to read the file and remove a specified section (defined by an input variable) and then save the modified file. So, for example, if the input was 'Section2', the resulting file would end up like this:
Code:
[Section1]
PropA=123
PropB=456
PropC=789
[Section3]
PropA=000
PropB=111
PropC=222
If the specified section does not exist then the file is not modified.
Any ideas in how to do this with a combination of awk and sed?
Re: Shell scripting challenge
Shell script?
Unix is a way of thinking not an operating system, you should use the right tool for the job. Good shell scripts are awful to write and maintain, so most people end up using Bash scripts which are heavyweight, slow and system specific. Try a better tool if possible, I think this should be close enough for you to hack into what you want with a few Googles about the ruby language:
Code:
#!/usr/bin/ruby
sectionName = ARGV[0]
fileName = "datafile"
inSection = false
newContents = []
File.open( fileName ).each() {
| line |
if line =~ /\[(.*)\]/
inSection = ($1==sectionName)
end
newContents << line if !inSection
}
file = File.open( fileName, "w" )
newContents.each() {
| line |
file.write( line )
}
edit: I didn't like the substring match() for seeing if you are in the correct section. The =~ regex operator has parenthesis in the regex which extracts the section name into $1 in the next block, so just compare that to the expected string.
Re: Shell scripting challenge
Many thanks! I'll give that a go.
Re: Shell scripting challenge
Started writing an answer using AWK, but then realised it's just a standard INI file, right?
http://www.pixelbeat.org/programs/crudini/
Code:
crudini --del filename Section2
job done. I know it's not really the purpose of the thread, but if it's something you need to use in production rather than just a code challenge, then why not leverage someone else's hard work?
Re: Shell scripting challenge
Yeah, it's just like a normal INI file but happens to be on a Linux server. I've got a long awk line that now does the job too if anyone is interested in an awk-based solution:
Code:
awk 'BEGIN { FOUND=0 } /^\[Section2\]$/ {FOUND=1;next} /^\[.*\]$/ {FOUND=0} (if (FOUND==0) {print $0}; next}' input_file.cfg > input_file.cfg.new
This will create a new file, input_file.cfg.new, based on the processed input_file.cfg. So I guess a one-liner would look like this:
Code:
awk 'BEGIN { FOUND=0 } /^\[Section2\]$/ {FOUND=1;next} /^\[.*\]$/ {FOUND=0} (if (FOUND==0) {print $0}; next}' input_file.cfg > input_file.cfg.new; rm -f input_file.cfg; mv input_file.cfg.new input_file.cfg