3

Is it possible to copy the whole rows of File1 in a new File3 following the instruction given by File2 by using a simple bash script using sed or awk?

File1: /*two or more columns*/
AC    456324
DC    689712
GH    123677
KL    236587

File2: /*one column*/
AC
DC

File3: 
AC    456324
DC    689712

I'm actually performing this using Python dictionaries and I wondered if you knew a simple way out.

5

With grep

grep -Ff File2 File1

With awk

awk 'NR==FNR {a[$1]++;next} a[$1]' File2 File1
2

You can use join to combine rows from two files by joining them where a particular column has the same value in both files. Note that the input files need to be sorted by the values in that column..

join File1 File2

If the files aren't sorted, in bash/ksh93/zsh:

join <(sort File1) <(sort File2)

Here the field to join is the one that contains AC, DC, etc. Here's an example if the field to join is column 3 in File1 with column 2 in File2.

join -1 3 -2 2 <(sort -k3,3 File1) <(sort -k 2,2 File2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.