This script reads the lines and stores a common prefix at each iteration:
# read a line into the variable "prefix", split at slashes IFS=/ read -a prefix # while there are more lines, one after another read them into "next", # also split at slashes while IFS=/ read -a next; do new_prefix=() # for all indexes in prefix for ((i=0; i < "${#prefix[@]}"; ++i)); do # if the word in the new line matches the old one if [[ "${prefix[i]}" == "${next[i]}" ]]; then # then append to the new prefix new_prefix+=("${prefix[i]}") else # otherwise break out of the loop break fi done prefix=("${new_prefix[@]}") done # join an array function join { # copied from: http:
Example:
$ ./x.sh <<eof /home/nicool/Desktop1/file1.txt /home/nicool/Desktop2/dir1/file1.txt /home/nicool/Desktop3/dir1/dir2/file1.txt eof /home/nicool
source share