2

I'd like to use awk to process multiple files such as
File 1:

1 1.045
2 1.033
3 1.029

File 2:

1 1.078
2 1.080
3 1.090

but I'm interested in storing a specific field from each file and then printing them all out on one line. For example, I'd like the second field of the second line in both files so that the output would be:

1.033 1.080

Can I get awk to store the field in question from each file in a separate variable or in separate fields of an array? I tried:

awk '
BEGIN{}
FNR==2{var1=$2;nextfile}
FNR==2{var2=$2}
END{printf "%6.3f    %6.3f\n", var1,var2}' file1 file2

but this overwrites var1 with the field from the second file and never processes for var2.

4 Answers 4

2

In your example the third line is never evaluated, you could solve it like this:

awk '
BEGIN{}
FNR==2 && !var1 {var1=$2;nextfile}
FNR==2{var2=$2}
END{printf "%6.3f    %6.3f\n", var1,var2}' file1 file2

BUT, this approach is hard to generalize, I would rather do it like this:

awk 'FNR==row { printf "%6.3f    ", $col } END { printf "\n" }' row=2 col=2 file1 file2

Output:

1.033     1.080
Sign up to request clarification or add additional context in comments.

Comments

2

A different approach:

$ paste file1 file2 | awk 'NR==2{print $2,$4}'
1.033 1.080

Comments

0

do you want this?

awk 'NR==FNR{a[$1]=$2;next}$1 in a{print a[$1],$2}' file1 file2

outputs:

1.045 1.078
1.033 1.080
1.029 1.090

1 Comment

He just wants field 2 of line 2 in each file @Kent
0

Another approach to try:

awk '{p=$2; getline<f} NR==2{print p,$2; exit}' f=file2 file1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.