Output lines from file1 based on file2

March 2, 2011 at 14:09:24
Specs: Windows XP
I have two files. file1:

2
3
5

and file2:

first
second
third
fourth
fifth

I'd like to be able to input from the two files and get the following output:

second
third
fifth

How can I do that?


See More: Output lines from file1 based on file2

Report •

#1
March 2, 2011 at 14:19:15
I found a solution:

awk 'FNR==NR{_[++d]=$0;next}{for(i in _) if(FNR==_[i]) print}' file1 file2

If anyone has a better one, I'd still like to see it.


Report •

#2
March 2, 2011 at 15:30:35
Anything that supports arrays is a candidate - such as korn/bash shell arrays. Can't say it's better than an awk solution - just different:

#!/bin/bash

d=1
while read line
do
   al[d++]=$line
done < file2

while read line
do
   echo ${al[$line]}
done < file1


Report •
Related Solutions


Ask Question