0

I'm looking to compare two strings and capture the common part e.g.

  • FILE0000010985.LOG
  • FILE0000010999.LOG
  • FILE0000011000.LOG

If I compare 1 to 2, I want the output to be FILE00000109, but if I compare 1 to 3, the output would be 2 characters less FILE000001

It's capturing the common prefix I suppose, but the strings are unknown to me, so it's not just as simple as using Bash's substring matching features etc.

2

3 Answers 3

1

Pure bash solution. Notice that the output for 1 and 2 is FILE00000109, not FILE0000010.

#!/bin/bash
arr=(FILE0000010985.LOG
     FILE0000010999.LOG
     FILE0000011000.LOG
    )
for (( i=0; i<${#arr[@]}; ++i )) ; do
    for (( j=i + 1; j<${#arr[@]}; ++j )) ; do
        x=${arr[i]}
        y=${arr[j]}
        p=0
        while [[ ${x:0:p} == ${y:0:p} ]] ; do 
            (( ++p ))
        done
        echo $x $y : ${x:0:p-1}
    done
done
0
0

To compare each line to previous starting from second:

awk '
    NR==1{
        split($0,U,"")
        next}
    {
        s=split($0,A,"")
        f=1
        if(length(U)>s)
            s=length(U)
        for(i=1;i<=s;i++)
            if(A[i]==U[i]&&f!=0)
                printf("%s",A[i])
            else {
                f=0
                U[i]=A[i]}
        print ""}
'
0

If the two files are guaranteed to be differing one possibility is

f1=FILE0000010985.LOG
f2=FILE0000010999.LOG

for ((l=0; l<${#f1}; l++))
do [[ ${f1:0:l} != "${f2:0:l}" ]] && break
done
printf "%s\n" "${f1:0:l-1}"

(If files may be equal an additional test has to be added.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .