Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk to pull specific lines from a file

Tags:

awk

line

I have two files, one file is my data, and the other file is a list of line numbers that I want to extract from my data file. Can I use awk to read in my lines file, and then extract the lines that match the line numbers?

Example: Data file:

This is the first line of my data
This is the second line of my data
This is the third line of my data
This is the fourth line of my data
This is the fifth line of my data

Line numbers file

1
4
5

Output:

This is the first line of my data
This is the fourth line of my data
This is the fifth line of my data

I've only ever used command line awk and sed for really simple stuff. This is way beyond me and I have been googling for an hour without an answer.

like image 258
Davy Kavanagh Avatar asked Aug 29 '12 16:08

Davy Kavanagh


1 Answers

awk 'NR == FNR {nums[$1]; next} FNR in nums' numberfile datafile

simply referring to an array subscript creates the entry. Looping over the first file, while NR (record number) is equal to FNR (file record number) using the next statement stores all the line numbers in the array. After that when FNR of the second file is present in the array (true) the line is printed (which is the default action for "true").

like image 173
Dennis Williamson Avatar answered Oct 12 '22 23:10

Dennis Williamson