'Pass number of for loop elements to external command

I'm using for loop to iterate through .txt files in a directory and grab specified rows from the files. Afterwards the output is passed to pr command in order to print it as a table. Everything works fine, however I'm manually specifying the number of columns that the table should contain. This is cumbersome when the number of files is not constant.

The command I'm using:

for f in *txt; do awk -F"\t" 'FNR ~ /^(2|6|9)$/{print $2}' $f; done | pr -ts --column 4

How should I modify the command to replace '4' with elements number?

Edit: The fundamental question was if one can provide matching files number to function outside the loop. Seeing the solutions I guess it is not possible to work around the problem. Until this conclusion the structure of the files was not really relevant. However taking the above into account, I'm providing the files structure below.

Sample file.txt:

Irrelevant1 text
Placebo 1222327
Irrelevant1 text
Irrelevant2 text
Irrelevant3 text
Treatment1  105956
Irrelevant1 text
Irrelevant2 text
Treatment2  49271
Irrelevant1 text
Irrelevant2 text

The for loop generates the following from 4 *txt files:

1222327
105956
49271
969136
169119
9672
1297357
237210
11581
1189529
232095
13891

Expected pr output using a dynamically generated --column 4:

1222327 969136  1297357 1189529
105956  169119  237210  232095
49271   9672    11581   13891


Solution 1:[1]

You could just run ls and pipe the output to wc -l. Then once you've got that number you can assign it to a variable and place that variable in your command.

num=$(ls *.txt | wc -l)

I forget how to place bash variables in AWK, but I think you can do that. If not, respond back and I'll try to find a different answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1