Thursday, 30 January 2014

AWK string manipulations

The below script is used to scan a full text file line by line for a certain pattern.
Once this pattern is found,
The script does another pattern matching to do another change in that same line.

[root@khofo05 sherif]$  awk -v FILENAME=./server.xml_20131127_1 -f ./change_ds.awk >server.xml
[root@khofo05 sherif]$ cat change_ds.awk
BEGIN{
        i=0;
        line="";
        while (getline line < FILENAME)
        {
                gotit=match(line,"DB1");
                if (gotit == 0)
                {
                        print(line);
                }
                else if (gotit > 0 )
                {
                        #print ("match------",line);
                        newsvr=gsub("db111oracle.example.com","db123oracle.example.com",line);
                        newsid=gsub("DB1","DB3",line);
                        #print (newsvr,newsid,line);
                        print (line);
                        #break;
                }
        }
}
[root@khofo05 sherif]$



The above is an example for a mass change in a server.xml file for changing a Datasource definition from a SID/host to another SID/host.
Would be useful if multiple datasources are involved.

1 comment:

  1. Anther good script based on same idea used to edit puppet yaml files (13 files for one project in that case !)

    [root@feanor role_appserver_tcserver]# cat put_in_wily.sh
    for FILE in `ls group*.yaml`
    do
    awk -f awk_script.awk $FILE >${FILE}_fix
    mv ${FILE}_fix $FILE
    done
    [root@feanor role_appserver_tcserver]#

    [root@feanor role_appserver_tcserver]# cat awk_script.awk
    BEGIN{
    while (getline line)
    {
    split(line,yaml_field,"::");
    linebefore=match(line,"instanceType");
    #print(linebefore);
    if(linebefore > 0)
    {
    print line;
    print "tcserver::" yaml_field[2] "::wilyJavaOpts: '-javaagent:/opt/wily/Tomcat907/Agent.jar -Dcom.wily.introscope.agent.agentName=%{::hostname}_" yaml_field[2] " -Dcom.wily.introscope.agentProfile=/opt/wily/Tomcat907/core/config/IntroscopeAgent.profile'";
    }
    else
    {
    print line;
    }
    }

    }
    [root@feanor role_appserver_tcserver]#

    ReplyDelete