1

File1 (keywords present in it (after 2nd comma) for picking Ex: GOLD, BRO, ...)

File2 (extraction of lines from here)

File1: 
ABC,123,GOLD,20171201,GOLDFUTURE
ABC,467,SILVER,20171201,SILVERFUTURE
ABC,987,BRO,20171201,BROFUTURE

File2:
XYZ,32,RUBY,20171201,RUBY  
XYZ,33,GOLD,20171201,GOLD
XYZ,34,CEMENT,20171201,CEMENT
XYZ,35,PILLAR,20171201,pillar  
XYZ,36,CNBC,20171201,CNBC
XYZ,37,CBX,20171201,CBX
XYZ,38,BRO,20171201,BRO

I want Linux commands(awk-sed-cat-grep etc) to get output file: which is:

XYZ,33,GOLD,20171201,GOLD
XYZ,38,BRO,20171201,BRO

I have found commands online:

  1. grep -F -f File1 File2
  2. awk 'FNR==NR {a[$0];next} ($NF in a)' File1 File2
  3. awk 'FNR==NR {a[$0];next} ($0 in a)' File1 File2
  4. diff File1 File2

In the point 3. I am picking up whole lines from File1 for comparison, is there any way to pickup a keyword after comma? Or is there any way to insert File separator in the awk command of point 2.

sumit
  • 1
  • 3
  • what are the rules to get the output file? – Ben Dec 12 '17 at 05:16
  • you can change the 3rd command to suit your case.. use `,` as delimiter and use 3rd field instead of entire line as key.. see http://backreference.org/2010/02/10/idiomatic-awk/ for some details on this – Sundeep Dec 12 '17 at 05:17
  • and I think we should do a community wiki to create a canonical answer for such questions.. not able to find exact duplicate for this question, but creating one Q&A with different variations can help to close all such questions :) – Sundeep Dec 12 '17 at 05:19
  • @Sundeep thats what I have asked.. How do i use delimiter in it ? I tried but it gives error ? using 'awk -F "," ' but this is not working correctly. – sumit Dec 12 '17 at 05:19
  • show us complete command you tried and also copy paste the error you got.. – Sundeep Dec 12 '17 at 05:20
  • @Sundeep Agreed to create community wiki for such questions. – sumit Dec 12 '17 at 05:20
  • I believe that's what "stackoverflow documentation" was intended to provide. In the mean time, answers are still valid, and can be collapsed with duplicate identification as time goes by. @sumit, what does "not working correctly" mean? What exactly did you try using `awk -F` ? Include it in your question. – ghoti Dec 12 '17 at 05:26

1 Answers1

0

Could you please try following and let me know if this helps you.

awk -F, 'FNR==NR{a[$3];next} ($3 in a)' File1  File2
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 1
    You don't actually need to *set* `a[$3]` to anything. Simply mentioning it is enough to cause the key to exist in the array, which is all you need for `$3 in a`. – ghoti Dec 12 '17 at 05:34
  • @ghoti, thanks for letting me know sir, done changed it now. – RavinderSingh13 Dec 12 '17 at 05:47