shell - replacing specific value (from another file) using awk -


i have following file.

file1

a b 1 c d 2 e f 3 

file2

x l y m z n 

i want replace 1 x @ time , save in file3. next time 1 y , save in file4.

then files like

file3

a b x c d 2 e f 3 

file4

a b y c d 2 e f 3 

once finished x, y, z 2 l, m , n.

i start inserts not replace.

awk -v r=1 -v c=3 -v val=x -f, '     begin{ofs=" "}; nr != r; nr == r {$c = val; print} ' file1 >file3 

here's gnu awk script ( because uses multidimensional arrays, array ordering ) want:

#!/usr/bin/awk -f  begin { fcnt=3 }  fnr==nr { for(i=1;i<=nf;i++) f2[i][nr]=$i; next }  {     fout[fnr][1] = $0     ff = $nf     if(ff in f2) {         for( r in f2[ff]) {             $nf = f2[ff][r]             fout[fnr][fcnt++] = $0         }     } }  end {     for(f=fcnt-1;f>=3;f--) {         for( row in fout ) {             if( fout[row][f] != "" ) out = fout[row][f]             else out = fout[row][1]             print out > "file" f         }     } } 

i made @ least 1 major assumption input data:

  • the field number in file2 corresponds value needs replaced in file1. example, x field 1 in file2, , 1 needs replacing in output files.

here's breakdown:

  • set fcnt=3 in begin block.
  • fnr==nr - store contents of file2 in f2 array (field number, line number).
  • store original f1 line in fout (line number,1) - 1 special, available array position ( because fcnt starts @ 3 ).
  • save off $nf ff because it's going reset
  • whenever ff field number in first subscript of f2 array, reset $nf value file2 , assign result fout @ (line number, file number) $0 ( recomputed ).
  • in end, loop on fcnt in reverse order, , either set out replaced line value or original line value in row order, print out desired filename.

it run gawk -f script.awk file2 file1 ( notice file order ). following output:

$ cat file[3-8] b x c d 2 e f 3 b y c d 2 e f 3 b z c d 2 e f 3 b 1 c d l e f 3 b 1 c d m e f 3 b 1 c d n e f 3 

this made more efficient memory performing lookup in end block, wanted take advantage of $0 recompute instead of needing calls split in end.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -