Shaan Shaan - 2 years ago 93
Bash Question

Print all lines in "file2" which have line number stored in "file1" $2


count line_num
xy 55
ab 67



I want to print 55, 67 line numbers of file2

am trying:

while read file_name; do
line_num=`echo $file_name | awk '{print $2}'`
awk 'NR==$line_num{print;exit}' file2 >> file3.txt
done < file1

but it's not working!

Answer Source

You can use awk to read the line numbers in a loop and sed to print out the specific lines:

while read a; do sed -n ${a}p f2.txt; done < <(awk 'NR>1{print$2}' f1.txt)

If you have a bigger file, performance can be an issue as Ed pointed out, in that case you can use awk alone:

awk 'NR==FNR{if(NR>1)l[$2]=1;next}{if(l[FNR])print $0}' f1.txt f2.txt

Another way, is to use xargs:

awk 'NR>1{print $2}' f1.txt | xargs -n1 -I {} sed -n {}p f2.txt

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download