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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
With grep
grep -Ff File2 File1
With awk
awk 'NR==FNR {a[$1]++;next} a[$1]' File2 File1
Method 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)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0