How to use awk through multiple files

awktext processing

I want a solution for the general case (N folder)

I'm using awk to process a file and extract its content and put it in a variable then echo it:

This is the file:

H1 H2 H3 H4 H5 H6 H7 H8 H9
not important
not
not

This is the code:

$value1=awk '/H1/ { print $1}' file
$value2=awk '/H1/ { print $2}' file
$value3=awk '/H1/ { print $3}' file
echo $value1
echo $value2
echo $value3

I get the result:

H1
H2
H3

My question if I have multiple files with the same format (not the exact content, the same format) with the file and which is located in different folders but the same name:

/folder1
file
/folder2
file
/folder3
file

How can I echo the first 3 values of the H1 line but from each file in those folders so I get 9 results?

Best Answer

I wonder whether you’re leaving something out of the question, because you seem to be doing more work than you need to for what you say you want to do.  If I’m understanding you correctly.

If all you want to do is output (echo) the first three fields (values) from the line in the file that contains H1 (assuming that there is only one such line), all you need to do is

awk '/H1/ { print $1, $2, $3 }' input_file

or, if you want the values on three separate lines,

awk '/H1/ { print $1; print $2; print $3 }' input_file

To achieve the same result for multiple files, just list their names, for example, using brace expansion:

awk '/H1/ { print $1; print $2; print $3 }' /folder{1,2,3}/file

or use a wildcard, as the other answers suggested:

awk '/H1/ { print $1; print $2; print $3 }' /folder?/file

If you require that the values be assigned to variables, so you can manipulate them in your script, you need to explain your requirements more clearly.

Related Question