On Thursday 1 May 2008 16:27, robin.vobruba@[EMAIL PROTECTED]
wrote:
> hello everyone!
> I need to fix some things in a piece of generated code. I think it has
> to be done with awk, as its a multi line thing, for which sed seems to
> be bad. I have to replace some values in functions, according to the
> function name. so basically i have the generated code file
> (simplifyed):
> [code]
> blabla Name_2 blabla {
> aaaa
> bbbb
> cccc
> blabla Value blabla
> dddd
> }
>
>
> blabla Name_1 blabla {
> tttt
> wwww
> ssss
> cccc
> blabla Value blabla
> ssss
>
>
> blabla Name_3 blabla {
> xxxx
> qqqq
> blabla Value blabla
> llll
> }
> [/code]
>
> and a substitution map somehow like this (doesnt have ot be in this
> form, as i have to write it manually anyway):
> [code]
> Name_1 Value_x
> Name_2 Value_z
> Name_3 Value_y
> [/code]
>
> The first appearance of Value that comes after Name_1 has to be
> changed to read Value_x and so forth. It could be done with one awk
> invocation for each substitution, that would not be a problem, as it
> are only about 8 of them. The thing is, i have newer used awk (except
> copy and paste).
This is highly dependent upon the format of your input. Since you say it's
generated code, I assume that its format is known in advance and resembles
the format you show above. Also, I assume that none of the strings you're
looking for appears elsewhere as a substring of something else (ie, you
have no "aaaValueBLAH" or "fooName_3bar" in your input). If these
assumptions are not correct, then you need to provide a more detailed
specification of the problem. Otherwise, try this:
awk '
BEGIN { # define the mappings
m["Name_1"]="Value_x";
m["Name_2"]="Value_y";
m["Name_3"]="Value_z"; }
# check whether the line contains the key;
# if so, set the replacement string for that key
match($0,/Name_(1|2|3)/) {r=m[substr($0,RSTART,RLENGTH)]}
# do the replacement, if any, and print
{gsub(/Value/,r)} 1' yourfile
Of course, you have to rewrite the BEGIN section and the regular
expression
inside match() to adapt them to your actual values.
Running the code on your sample input, I get this:
blabla Name_2 blabla {
aaaa
bbbb
cccc
blabla Value_y blabla
dddd
}
blabla Name_1 blabla {
tttt
wwww
ssss
cccc
blabla Value_x blabla
ssss
blabla Name_3 blabla {
xxxx
qqqq
blabla Value_z blabla
llll
}
Remember that it's *not* a general solution (which would require, more or
less, writing a parser for your input language); rather, it's a solution
that makes some assumptions and is specifically tailored to the sample
input you showed.
--
All the commands are tested with bash and GNU tools, so they may use
nonstandard features. I try to mention when something is nonstandard (if
I'm aware of that), but I may miss something. Corrections are welcome.


|