Home > Net >  How to replace only a column and for the rows contains specific values
How to replace only a column and for the rows contains specific values

Time:08-22

I have the file with | delimited, and am trying to perform below logic

cat list.txt

101
102
103

LIST=`cat list.txt`

Input file

1|Anand|101|1001    
2|Raj|103|1002    
3|Unix|110|101

Expected result

1|Anand|101|1001    
2|Raj|103|1002    
3|Unix|UNKNOWN|101

I tried 2 methods,

  1. using fgrep by passing list.txt as input and tried to segregate as 2 files. One matches the list and second not matching and post that non matching file using awk & gsub replacing the 3rd column with UNKNOWN, but issue here is in 3rd row 4th column contains the value available in list.txt, so not able to get expected result

  2. Tried using one liner awk by passing list in -v VAR. Here no changes in the results.

awk -F"|" -v VAR="$LIST" '{if($3 !~ $VAR) {{{gsub(/.*/,"UNKNOWN", $3)1} else { print 0}' input_file

Can you please suggest me how to attain the expected results

CodePudding user response:

There is no need to use cat to read complete file in a variable.

You may just use this awk:

awk 'BEGIN {FS=OFS="|"}
FNR==NR {a[$1]; next}
!($3 in a) {$3 = "UKNNOWN"} 1' list.txt input_file

1|Anand|101|1001
2|Raj|103|1002
3|Unix|UKNNOWN|101
  • Related