Passing input parameter from a config file in AWK command Passing input parameter from a config file in AWK command unix unix

Passing input parameter from a config file in AWK command


One easiest way is to create file, which contains position start and no of chars like below, you don't have to write so many time one=substr($0,start,n_char);:

Input:

$ cat infile k12582927001611USNAk12582990001497INASk12583053001161LNEU

Position file:

$ cat pos 1,12,1012,416,218

One-liner:

$ awk 'BEGIN{FS=OFS=","}FNR==NR{pos[++i,"s"]=$1;pos[i,"e"]=$2+0?$2:length;next}{for(j=1; j<=i; j++) printf("%s%s", substr($0,pos[j,"s"],pos[j,"e"]),j==i?ORS:OFS)}' pos infile k,1258292700,1611,US,NAk,1258299000,1497,IN,ASk,1258305300,1161,LN,EU

Better Readable :

awk 'BEGIN{            FS=OFS=","     }     FNR==NR{            pos[++i,"s"]=$1;            pos[i,"e"]=$2+0?$2:length;            next     }     {          for(j=1; j<=i; j++)              printf("%s%s", substr($0,pos[j,"s"],pos[j,"e"]),j==i?ORS:OFS)     }' pos infile


I've reorganized it as

cat cfg.awk

{    one=substr($0,1,1)   two=substr($0,2,10)   three=substr($0,12,4)   four=substr($0,16,2)   rest=substr($0,18)}

cat printer.awk

{ printf ("%s,%s,%s,%s,%s\n", one, two, three, four, rest) }

run as

awk -f cfg.awk -f printer.awk data.txt

output

k,1258292700,1611,US,NAk,1258299000,1497,IN,ASk,1258305300,1161,LN,EU

The only difference is that you need to add opening/closing { .. } (curly braces) around your var=substr code.

IHTH


Following awk may also help you in same.

awk 'function check(val, re){  split(val, array,",");  re=array[1] && array[2]?substr($0,array[1],array[2]):substr($0,array[1]);  return re}FNR==NR{  match($0,/\(.*\)/);  a[FNR]=substr($0,RSTART+4,RLENGTH-5);  count++;  next}{for(i=1;i<=count;i++){  val=val?val "," check(a[i]):check(a[i])};  print val;  val=""}' Input_file_config   Input_file

Output will be as follows.

k,1258292700,1611,US,NAk,1258299000,1497,IN,ASk,1258305300,1161,LN,EU