Linux – Get some rows

Get some rows… here is a solution to the problem.

Get some rows

I

need help with: I have this kind of file, named file-1

1
++++++^^++++
++++++++++++
+++++++++^^^
^^++++++++++

2
++++++++++++
^^^+++++^^^^
^^^^^^^+++++
+++++^^^++^+

Now I want to print out the part with the same starting number as another file named file-2.
Let’s say file-2 contains 1 value, so I need to get this output:

1
++++++^^++++
++++++++++++
+++++++++^^^
^^++++++++++

Can someone give me some advice?

Solution

$ awk -v RS='' 'NR==FNR{split($0, a, /\n/); next}; $1 in a' file-{2,1}
1
++++++^^++++
++++++++++++
+++++++++^^^
^^++++++++++

file-2 contains index: row by row

1
3
5

Description:

  • RS='' tells awk to read multiple rows of records
  • NR==FNR reads file-2 as a line, so we should split \n, and save the result to array a
  • next skips the remaining commands and prepares to read file-1
  • $1 in A Tests whether the first column of file-1 is in array A
  • file-{2,1} We should read file-2 first to get all indexes

Related Problems and Solutions