Taylor Borgfeldt Taylor Borgfeldt - 27 days ago 10
Linux Question

Use part of a column in one file as search term in other file

I have two files. The output file I am searching has earthquake locations and has the following format:

19090212 1323 30.12 36 19.41 103 28.24 7.29 0.00 4 149 25.8 0.02 5.7 9.8 D - 0
19090216 1828 49.61 36 13.27 101 35.38 10.94 0.00 13 54 38.5 0.07 0.3 0.7 B 0
19090711 2114 54.11 35 1.07 99 56.42 7.00 0.00 7 177 18.7 4.00 63.3 53.2 D # 0


I want to use the last 6 digits of the first column (i.e. '090418' out of '19090418') with the first 3 digits of the second column (i.e. '072' out of '0728') as my search term. The file I am searching has the following format:

SC17 P 090212132329.89
X25A P 090212132330.50

AMTX P 090216182814.12
X29A P 090216182813.70
Y28A P 090216182822.36
MSTX P 090216182826.80
Y27A P 090216182831.43


After I search the second file for the term, I need to figure out how many lines are in that section. So for this example, if I were searching the terms shown for the second file above, I want to know there are 2 lines for 090212132 and 5 lines for 090216182.

This is my first post, so please let me know how I can improve clarity or conciseness in my posts. Thanks for the help!

Answer

awk to the rescue!

$ awk 'NR==FNR{a[substr($1,3) substr($2,1,3)]; next} 
              {k=substr($3,1,9)} 
        k in a{a[k]++} 
           END{for(k in a) if(a[k]>0) print k,a[k]}' file1 file2

with your input files, there is no output as expected.

Comments