Alby
Alby

Reputation: 5742

How to extract the given list of lines from a file without writing a script

The task is this:

For a given list of numbers(potentially very long) like this:

1
5
8
...(very long)

extract the corresponding line from the second file.

I had to write a simple python code to accomplish this task, but I was wondering if there is a way to do this without resorting to the scripts. Something along the lines of using process substitutions and combination of coreutils:

SOME_COMMANDLINE_FU <(cat first_file) second_file

The below is the python code I wrote:

#!/usr/bin/env python
import sys
# select.py <LINE_INDEX> <FILE>

line_numbers = open(sys.argv[1],"r").readlines()
line_numbers = map(int, line_numbers)

with open(sys.argv[2],"r") as f:
    index = 1
    for line in f:
        if index in line_numbers:
            print line,
        index = index + 1

Upvotes: 0

Views: 57

Answers (2)

fedorqui
fedorqui

Reputation: 289745

Just loop through the numbers file and store them in an array. Then, read the seconf file and check on each line if its number is in the stored array:

awk 'FNR==NR {a[$1]; next} FNR in a' file1 file2

The FNR==NR {} trick makes {} to be executed when reading the first file. Then, the rest is executed when reading the second one. More info in Idiomatic awk.

Upvotes: 3

mhavu
mhavu

Reputation: 41

I guess that depends on what is considered a script. One way to extract the lines is to use awk:

awk '{system("awk NR=="$1" second_file")}' first_file

Upvotes: 0

Related Questions