How do I compare file names in two directories in shell script?

前端 未结 5 827
有刺的猬
有刺的猬 2021-01-31 05:39

Right now, this is what my code looks like:

#!/bin/bash

Dir1=$1
Dir2=$2

for file1 in $Dir1/*; do
    for file2 in $Dir2/*; do
        if [[ $file1 == $file2 ]]         


        
相关标签:
5条回答
  • 2021-01-31 05:57

    I just tested this and it worked:

    DIR1=$(ls dir1)
    DIR2=$(ls dir2)
    
    for i in $DIR1; do
        for j in $DIR2; do
            if [[ $i == $j ]]; then
                echo "$i == $j"
            fi
        done
    done
    
    0 讨论(0)
  • 2021-01-31 06:01

    Files that are in both Dir1 and Dir2:

    find "$Dir1/" "$Dir2/" -printf '%P\n' | sort | uniq -d
    

    Files that are in Dir1 but not in Dir2:

    find "$Dir1/" "$Dir2/" "$Dir2/" -printf '%P\n' | sort | uniq -u
    

    Files that are in Dir2 but not in Dir1:

    find "$Dir1/" "$Dir1/" "$Dir2/" -printf '%P\n' | sort | uniq -u
    
    0 讨论(0)
  • 2021-01-31 06:01

    It doesn't work because you're comparing variables that contain the directory prefix. Just remove the prefix before comparing:

    name1=${file1##*/}
    name2=${file2##*/}
    if [[ $name1 == $name2 ]]; then
        echo "$name1 exists in both directories"
    fi
    

    Also, nested loops seems like an inefficient way to do this. You just need to get the filenames from one directory, and use a simple file existence check for the other directory.

    for file in $Dir1/*; do
        name=${file##*/}
        if [[ -f $Dir2/$name ]]; then
            echo "$name exists in both directories"
        fi
    done
    
    0 讨论(0)
  • 2021-01-31 06:02

    If you want to know what's common to two directories then this is another way with much less coding.

    #!/bin/bash
    
    comm -12 <(ls -F $1) <(ls -F $2)
    

    See man comm for more information about the comm utility.

    0 讨论(0)
  • 2021-01-31 06:02

    Your comparison fails because Dir1/foo is not the same as Dir2/foo. Instead, if you change to one directory, your * will expand to just the filenames:

    #!/bin/bash
    
    Dir1="$1"
    Dir2="$2"
    
    if ! cd "$Dir1"; then
      echo "ERROR: Couldn't find directory $Dir1" >&2
      exit 1
    fi
    
    if [[ ! "$Dir2" =~ ^/ ]]; then
      echo "ERROR: Second directory must be a full path." >&2
      exit 1
    fi
    
    for file1 in *; do
        if [ -f "$Dir2/$file1" ]; then
            echo "$file1 is contained in both directories"
        fi
    done
    

    Note that this only matches file names. If you want to make sure it's really the same file, you should use cmp to compare them.

    0 讨论(0)
提交回复
热议问题