Skip to content

Find the closest match between two files in unix

As a beginner i’m looking for a solution in shell scripting,

I have file1 with content as below lines:

timestamp6 serverName A: Session3: session closed for user grpname

timestamp5 serverName A: Session3: session opened for user grpname by jack

timestamp4 serverName A: Session2: session closed for user grpname

timestamp3 serverName A: Session2: session opened for user grpname by john

timestamp2 serverName A: Session1: session closed for user grpname

timestamp1 serverName A: Session1: session opened for user grpname by matt

And file2 with filenames and their modified timestamp.

Filename1 timestamp_x

Filename2 timestamp_y

Filename3 timestamp_z

I’m looking shell script solution where it can tell the closest match in timestamp in the between both files.

Like timestamp_x and timestamp_y comes in between timestamp_1 and timestamp_2.

Thanks

Advertisement

Answer

If your timestamps sort (possible with -M). sort file1 along with the content of file2 with the order of the two fields swapped. Then use grep with the context option to see what comes before/after:

(cat file1; sed 's/(.*) (.*)/2 1/' file2) | sort | egrep -C1 'timestamp_[x-z]'
User contributions licensed under: CC BY-SA
7 People found this is helpful