views:

44

answers:

3

Hi,

I have two files, should compare 1st column of file1 with 1st column of file2 and the resultant file should be file2

For example:

  • file1

    apple
    banana
    Mango
    potato
    tomato

  • file 2

    apple:fruit
    brinjal: vegetable
    lady's finger: vegetable
    orange: fruit
    tomato: vegetable
    potato: vegetable

Resultant file should look something like this:

apple:fruit
tomato: vegetable
potato: vegetable

any ideas on this would be appreciated

Thanks

A: 
grep "$(cat file1.txt)" file2.txt
Alberto Zaccagni
`grep -f file1.txt file2.txt`
Dennis Williamson
I'm getting a error "Illegal variable name"
Shruti
@Dennis: oh, nice, did not know of that flag, thank you :P
Alberto Zaccagni
@Shruti: what shell are you using? I did that in bash 4.1.5 and it worked.
Alberto Zaccagni
i'm using C shell I have tried it in bash too, i'm getting the same error
Shruti
@Shruti: Alberto's version won't work in csh, but the version in my comment should. You can also try this variation on Alberto's version: `grep "\`cat file1.txt\`" file2.txt`. It would be really weird if you're getting that error in Bash.
Dennis Williamson
using grep may not be suitable since grep finds the whole line for the pattern.
ghostdog74
+1  A: 

In Bash, ksh, zsh:

join -t: <(sort file1) <(sort file2)

In other shells you will need to presort your files.

Dennis Williamson
+2  A: 

without the need to sort (less process creation)

$ awk -F":" 'FNR==NR{f[$0];next}($1 in f)' file file2
apple:fruit
tomato: vegetable
potato: vegetable
ghostdog74