Need help with a script to grep items in one file from another file

I have one master file "File1" with all such info in it. I need to grep each object under each list from another file "File2". Can anyone help me with a script for this.

File 1
------
List 1
     Object 1
     Object 2
List 2
     Object 3 
     Object 1
List 3
     Object 2
     Object 5
File2
-----
Object 1
Object 3
Object 4

I need to sort out info with the following result

List 1 has 1 objects from File2
List 2 has 2 objects from File2
List 3 has 0 objects from File2

Thanks in advance
Sam

Sounds like homework.
So where are you stuck?

--ahamed

It's for work actually. Trying to automate few things to make life easier based on the information received from the network switches. Those two files is an example of how the data would be. I am a novice at best in shell programming and wanted to see if there is a simple way this can be done through awk/sed?

Here is an awk program that might work for the posted sample input:

awk ' BEGIN {
        F = "file1"
        while ( (getline line < F) > 0 )
        {
                gsub(/^[ \t]*|[ \t]*$/, x, line)
                if ( line ~ /List/ )
                        L = line
                if ( line !~ /List/ )
                        A[L] = ( A[L] == "" ? line : A[L] "," line )
        }
        close (F)

        F = "file2"
        while ( (getline line < F) > 0 )
        {
                gsub(/^[ \t]*|[ \t]*$/, x, line)
                for ( k in A )
                {
                        n = split ( A[k], R, ",")
                        for ( j = 1; j <=n; j++ )
                        {
                                if ( line == R[j] )
                                        C[k]++
                        }
                }
        }
        close(F)

        for ( k in A )
                print k " has " (C[k] == "" ? 0 : C[k]) " objects from file2"
} '

Note: Replace file1 & file2 with actual input file names. Use nawk instead if you are on SunOS or Solaris.

1 Like

Is this how the actual data looks like? with space and tab and all? Cause it will matter while coding. A real data sample would help us better.

--ahamed

1 Like

Here is another one with awk:

awk '
NR==FNR {obj[$1$2]=1; fn=FILENAME; next}
/^List/ {
if(s!="") printf "%s has %d objects from %s\n",s,cnt,fn
s=$0; cnt=0
next
}
$1$2 in obj {cnt++}
END {
if(s!="") printf "%s has %d objects from %s\n",s,cnt,fn
}' File2 File1

Solaris needs /usr/xpg4/bin/awk or nawk.

1 Like