Sunday, January 30, 2022

[SOLVED] There are 2 folders.A and B has 7 txt files.There are 3 files same in two folder.Now need to remove 4 file from B which not there in A

Issue

Shell script:

#!/bin/bash

echo "Enter the path of 1st folder"
read filePath
echo "Enter the path of 2nd folder"
read filePath2

find $filePath $filePath2 -print | sort | uniq

if [[ -f $filePath && -f $filePath2 ]]
then
  while [ $filePath/*.txt != $filePath2/*.txt ]
  do
    rm -rf $filePath2/*.txt
  done
else
  echo "The File dose not exist or file not exist in that path"
fi

It is not working. Can you tell me right answer?


Solution

#!/bin/bash -e

# get the file list

cd "$1"
for i in *; do
    ! [[ -d "$i" ]] && keep_list+=("$i")
done

cd - >/dev/null
cd "$2"

for i in *; do
    [[ -d "$i" ]] && continue
    keep=

    for j in "${keep_list[@]}"; do
        if [[ "$i" == "$j" ]]; then
            keep=true
            break
        fi
    done

    if ! [[ "$keep" ]]; then
        do_rm=true
        rm_list+=("$i")
    fi
done

# print the list, and ask interactively for confirmation

if [[ "$do_rm" ]]; then
    printf '%s\n' "${rm_list[@]}"
    echo
    echo "these file names are not in $1, and will be REMOVED from $2"
    read -rp 'type yes to proceed: ' reply

    if [[ "$reply" == [Yy][Ee][Ss] ]]; then
        rm "${rm_list[@]}"
    else
        echo no files touched
    fi
else
    echo "nothing to remove: all file names in $2 are present in $1"
fi

Usage: ./script directory-a directory-b

Note that this only compares file names, not the actual contents of the files. You can compare the files' contents with: diff directory-a directory-b

edit: Updated to completely ignore sub-directories, as I think that is generally more useful (than comparing a directory to a file). To include sub—directories, remove the [[ -d "$i" ]] tests and add -r to rm.



Answered By - dan
Answer Checked By - Pedro (WPSolving Volunteer)