perl - Need to replace a specific column value of a file based on values in other columns of the file -
below content of file , below requirement based value in column no 1 , column no 5, want replace value in column 7 "1".
for example:
- if column 1="change" , column 5="defer", replace value in column 7 "1".
- if column 1="change" , column 5="defererence" replace value in column 7 "1".
- otherwise not row, keep is.
input file:
change|sinmg|1234|ewfew|def|fdfd|james|rewr|robert|3|fe change|sinmg|2345|ewfew|defer|venktraaammamamammama|3|rewr|beaey|3| nochange|sinmg|2323|ewfew|def|venktraaammamamammama|3|rewr|beaey|3|fe change|sinmg|3456|ewfew|defer|venktraaammamamammama|3|rewr|beaey|3| change|sinmg|2345|ewfew|defererence|venktraaammamamammama|3|rewr|beaey|3|
above sample make easier explain.however want pass values column 1 , column 5 file match against value in file. if matches, replace column 7 value "1" otherwise dont row, keep is.
i tried couple of options , not able achieve required results.
perl -f'\|' -i -lape 'if ($f[0] eq "change" && $f[4] eq "defer") { s/$f[6]/1/g;}' file_name
above command replacing values of 3 in file irrespective of fields. want replace 6th column value based on 1st column , 4th column passing different values 1st , 4th column in loop.
adding more information:
as mentioned me above, above example simplest form of problem make understand requirement. have file name "listfile" has got list of values column no 1 , column no 5 matching. if values in column no 1 , column no 5 sourcefile matches values passed file "listfile", solution should replace value in column no 7 "1". otherwise not row source file, keep is.
i tried below, unable achieve required.
#!/usr/bin/ksh line in $(cat dir/listfile) var1=$(echo $line | nawk -f"|" '{print $1}') var2=$(echo $line | nawk -f"|" '{print $2}') nawk -f"|" 'begin {ofs="|"} {if($1!="'"$var1"'" && $5!="'"$var2"'") {$8="1"; print $0;} else {print $0;}}' dir/sourcefile >> dir/sourcefile_revised done
no of records between original source file , revised source file after replacing column no 7 should same. thing values of column no 1 , 5 file listfile, need column no 7 value replaced "1".
thanks,
you can use awk
this.
awk -f'|' 'begin{ofs="|"}{if($1=="change"&&$5=="defer"){$7=1}{print}}' file
i realize need 5th column match "differerence"... following should work:
awk -f'|' 'begin{ofs="|"}{if($1=="change"&&$5=="defer"||$5=="defererence"){$7=1}{print}}' file
Comments
Post a Comment