2012-02-14 47 views
1

我有兩個字符串這樣發現兩個路徑字符串的殼最長匹配

/home/user/Desktop/aaaa/Final/ 
/home/user/Desktop/aaaa/folder3333/IMAG0486.jpg 

和我的結果字符串應該是這樣的

/home/user/Desktop/aaaa/Final/folder3333/IMAG0486.jpg 

意思,當我發現在最長匹配這種情況下

「/ home/user中/桌面/ AAAA」

然後我添加第二串

「folder3333/IMAG0486.jpg」

到拳頭串

和結果字符串的其餘部分被

/home/user/Desktop/aaaa/Final/folder3333/IMAG0486.jpg 

回答

0

/上的路徑拆分爲數組。迭代數組直到找到差異,將第二個數組的其餘部分添加到輸出中。我將代碼中的調試打印留下,刪除它們可以顯着縮短。

#! /bin/bash 
s1=/home/user/Desktop/aaaa/Final/ 
s2=/home/user/Desktop/aaaa/folder3333/IMAG0486.jpg 
expect=/home/user/Desktop/aaaa/Final/folder3333/IMAG0486.jpg 
out=$s1 

_IFS=$IFS 
IFS=/ 
parts1=($s1) 
parts2=($s2) 
IFS=$_IFS 

matching=1 
for ((i=0;i<${#parts2[@]};i++)) ; do 
    if [[ $matching && ${parts1[i]} == ${parts2[i]} ]] ; then 
     echo same ${parts2[i]} 
    else 
     echo different ${parts1[i]} ${parts2[i]} 
     matching=0 
     out+=${parts2[i]}/ 
    fi 
done 
out=${out%/} 

echo $expect 
echo $out 
0

This對我的作品,並已工作unit tests

path_common() 
{ 
    if [ -z "${2-}" ] 
    then 
     return 2 
    fi 

    # Remove repeated slashes 
    for param 
    do 
     param=$(printf %s. "$1" | tr -s "/") 
     set -- "[email protected]" "${param%.}" 
     shift 
    done 

    common_path=$1 
    shift 

    for param 
    do 
     while case ${param%/}/ in "${common_path%/}/"*) false;; esac; do 
      new_common_path=${common_path%/*} 
      if [ "$new_common_path" = "$common_path" ] 
      then 
       return 1 # Dead end 
      fi 
      common_path=$new_common_path 
     done 
    done 
    printf %s "$common_path" 
} 
0

低於其他解決方案可靠,但對於普通情況下正常工作:

#!/bin/bash 

p1="/home/user/Desktop/aaaa/Final/" 
p2="/home/user/Desktop/aaaa/folder3333/IMAG0486.jpg" 

printf "%s|%s" "$p1" "$p2" | sed -e 's_^\(\(.*\)\/.*\)|\2/\(.*\)$_\1\3_'