Search code examples
shellunixawkshksh

need help on unix Script to read a data from specific position and use the extracted in query


Input file:

ADSDWETTYT017775227ACG
ADSDWETTYT029635225HCG
ADSDWETTYC018525223JCG
ADSDWETTYC987415221ACG
ADSDWETTCC891235219ACG
ADSDWETTTT074565217ACG
ADSDWETTYT567895213ACG
ADSDWETTYH037535215ACG
ADSDWETTYC051595211ACG
ADSDWETTYT052465209ACG
ADSDWETTYT067595207ACG
ADSDWETTYT077515205ACG

need to check the 10 position on the file contain/start with T, if its start with "T" then i need to take the value from 14 char from 16.

from the above file am expecting the below output,

'5227','5225','5217','5213','5209','5207','5205'

this result i should assigned to some constant like (result below) and should be used in the query where clause like below,

result=$(awk '
        BEGIN{
        conf="" };
{       if(substr($0,10,1)=="T"){
        conf=substr($0,16,4);

{NT==1?s="'\''"conf:s=s"'\'','\''"conf}
}
}
END {print s"'\''"}
' $INPUT_FILE_PATH  

db2 "EXPORT TO ${OUTPUT_FILE}  OF DEL select STATUS FROM TRAN where TN_NR in (${result})"

I need some help to enhance the awk command and passing the constant in query where clause. kindly help.


Solution

  • With your shown samples, attempts; please try following awk code.

    awk -v s1="'" 'BEGIN{OFS=", "} substr($0,10,1)=="T"{val=(val?val OFS:"") (s1 substr($0,16,4) s1)} END{print val}'  Input_file
    

    Adding non-one liner form of above code:

    awk -v s1="'" '
    BEGIN{ OFS=", " }
    substr($0,10,1)=="T"{
      val=(val?val OFS:"") (s1 substr($0,16,4) s1)
    }
    END{
      print val
    }
    '  Input_file
    

    To save output of this code into a shell variable try following:

    value=$(awk -v s1="'" 'BEGIN{OFS=", "} substr($0,10,1)=="T"{val=(val?val OFS:"") (s1 substr($0,16,4) s1)} END{print val}' Input_file)

    Explanation: Adding detailed explanation for above code.

    awk -v s1="'" '             ##Starting awk program from here setting s1 to ' here.
    BEGIN{ OFS=", " }           ##Setting OFS as comma space here.
    substr($0,10,1)=="T"{       ##Checking condition if 10th character is T then do following.
      val=(val?val OFS:"") (s1 substr($0,16,4) s1) ##Creating val which has values from  current line as per OP requirement.
    }
    END{                        ##Starting END block of this program from here.
      print val                 ##Printing val here.
    }
    '  Input_file               ##Mentioning Input_file name here.