2

Would like to compare second field from F11.txt and first field from F22.txt then Print match cases as "Available" and non match cases as "NotFound" if the field $4 (file F11.txt) is null, if the field $4 (file F11.txt) is not null then print the lines of F11.txt as it is.

Inputs:

F11.txt
a,10,zzz
b,20,zzz,yyy
c,50,zzz

F22.txt
10,yyy
20,yyy
30,yyy
40,yyy

Have tried the below command, Thanks sat for help.

awk -F "," 'NR==FNR{a[$1]=$0;next}{print $0 "," (a[$2]?"Available":"NotFound")  }' f22.txt f11.txt

Got the below output

a,10,zzz,Available
b,20,zzz,yyy,Available
c,50,zzz,NotFound

where as b,20,zzz,yyy is match case but don’t want to override as "Available" as $4 is not null (empty)

Expected Output:

a,10,zzz,Avilable
b,20,zzz,yyy
c,50,zzz,NotFound
VNA
  • 605
  • 2
  • 8
  • 18

2 Answers2

1

I believe the script below does what you want

BEGIN {
    FS=OFS=","
}

NR==FNR {
    a[$1]=$0
    next
}

!$4 {
    $4 = (a[$2] ? "Available" : "NotFound")
}

1

Updated script to explicitely check for an empty fourth field (to allow for longer lines with an empty fourth field. Updated again to replace the empty fourth field instead of appending a field.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • Excellent Etan, Thanks a lot for good support !!! please provide some details the usage of "1" at the end of the command – VNA May 30 '14 at 05:01
  • 1
    @AVN `awk`'s default behavior on true condition is to print the line. Since `1` is always-true condition it gets interpreted as `{ print $0 }` and prints each line (you could even use 4, or 7, or any other nonzero value if you so prefer; 1 is just what people traditionally use) to suggest that action. – jaypal singh May 30 '14 at 17:30
  • 1
    Someone on SO, I forget who offhand, tends to use `7` for this instead of `1`. I kind of like that because it stands out a bit more and seems, to me at least, to read a little more like "pay attention this is doing something" than using `1` does. But I haven't convinced myself to actually start using it. – Etan Reisner May 30 '14 at 17:34
  • @EtanReisner You are probably referring to [Kent](http://stackoverflow.com/a/23681712/970195). `:)` – jaypal singh May 30 '14 at 18:10
0

Try this:

awk -F, '
NR==FNR {a[$1]=$0;next}
  NF==3 {print $0($2 in a?",Available":",NotFound");next}1
' F22.txt F11.txt
a,10,zzz,Available
b,20,zzz,yyy
c,50,zzz,NotFound
jaypal singh
  • 74,723
  • 23
  • 102
  • 147