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 infile1
. example,x
field 1 infile2
, ,1
needs replacing in output files.
here's breakdown:
- set
fcnt=3
inbegin
block. fnr==nr
- store contents offile2
inf2
array (field number, line number).- store original
f1
line infout
(line number,1) -1
special, available array position ( becausefcnt
starts @ 3 ). - save off
$nf
ff
because it's going reset - whenever
ff
field number in first subscript off2
array, reset$nf
valuefile2
, assign resultfout
@ (line number, file number)$0
( recomputed ). - in
end
, loop onfcnt
in reverse order, , either setout
replaced line value or original line value inrow
order, printout
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
Post a Comment