Extract rows from file based on row numbers stored in another file

Hi All,

I have a file which is like this:

rows.dat

1 2 3 4 5 6
3 4 5 6 7 8
7 8 9 0 4 3
2 3 4 5 6 7
1 2 3 4 5 6

I have another file with numbers like these (numbers.txt):

1
3
4
5

I want to read numbers.txt file line by line. The extract the row from rows.dat based on the number obtained from numbers.txt, and store in files with names of the rows.

Based on above example, this is what I intend to do:
My first number in numbers.txt is 1, so I create a file 1.num and copy the first row from rows.dat in it.

1.num

1 2 3 4 5 6

Then I go to second line in numbers.txt and get 3. I create a file 3.num and copy the third row from rows.dat file like this.

3.num

7 8 9 0 4 3

I keep doing it until the end of numbers.txt file

I have written the code for it, but it is not able to create separate files based on the row number. It copies all rows to another file

for i in `cat numbers.txt`
do
sed -n "$i p" rows.dat >> op.txt
done

I am doing this in Linux with BASH.

awk 'NR==FNR{a[FNR]=$0;next} {print a[$1] > $1 ".num"}' rows.dat numbers.txt
1 Like

If you want to stick to bash script you could do something like:

while read i
do
     sed -n "$i p" rows.dat > $i.num
done < numbers.txt

However, rdcwayx's solution it more efficient as the above runs sed once for each number in numbers.txt.

1 Like
$ awk '{print "sed -n "$0"p rows.dat > "$0".num"}' numbers.txt | sh
1 Like