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

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:


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:


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

  • you do it: paste f1.txt f2.txt f3.txt |awk {'blah blah'} – PersianGulf Sep 8 '14 at 8:52

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.


In the example case you described, something simple like following should work:

value1 = $(awk '/H1/ { print $1}' folder?/file)
value2 = $(awk '/H2/ { print $2}' folder?/file)
value3 = $(awk '/H3/ { print $3}' folder?/file)

You will get:

echo $value1
H1 H1 H1

and so on.


Could do it this way

for i in $(awk '/H1/{print "Variable"++x"="$x}' folder?/file); do
    eval $i
  • Any Reason this has been downvoted, leave a comment if you think this is wrong. – user78605 Sep 8 '14 at 13:55
  • This extracts $1 from /folder1/file, $2 from /folder2/file, and $3 from /folder3/file. I don’t think that’s what the question is asking for. – G-Man Says 'Reinstate Monica' Sep 8 '14 at 17:42
  • @G-Man oh yeah it isn't :(. This may be helpful to someone though so i'll leave it here. Explains the downvote at least :) – user78605 Sep 9 '14 at 7:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy