Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

bash - grep column from different files according to the first column value

I need help in extracting one column of numbers from many different files and display it in an output file.

Specifically, I want to extract the second column ($2) from each file, file1.txt, file2.txt etc., according the the value of the first column, then place all extracted columns in a one file, out.txt.

The problem is that the first column has different intervals in each file:

file:

0.50 x1
1.25 x2
1.50 x3
1.75 x4
2.00 x5

file2:

0.25 y1
0.50 y2
1.00 y3
1.25 y4
2.00 y5

Desired output:

0.25    y1
0.50 x1 y2
1.00    y3
1.25 x2 y4
1.50 x3
1.75 x4
2.00 x5 y5
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it using gawk and 2-d array in it as:

gawk 'FNR==NR{a[$1][0]=$2;a[$1][1]=1;next} {print $0,a[$1][0]; a[$1][1]=0;} END{for(i in a){if (a[i][1] == 1) print i,a[i][0];}}' file2 file1

Output:

0.50 x1 y2
1.25 x2 y4
1.50 x3 
1.75 x4 
2.00 x5 y5
1.00 y3
0.25 y1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...