Home > Back-end >  Is there a way tp go through files and comparing them two by two in bash script?
Is there a way tp go through files and comparing them two by two in bash script?

Time:09-28

I am new to bash scripting so I think there might be a way to do this but I couldn't find info on the web for exactly what I want.

I need to compare files in a folder and now I manually go through them and run:

diff -w file1 file2 > file_with_difference

What would make my life a lot easier would be something like this (pseudocode):

for eachfile in folder:
    diff -w filei filei 1 > file_with_differencei #the position of the file, because the name can vary randomly
                                                  
    i =1                                          #so it goes to 3vs4 next time through the loop, 
                                                  #and not 2vs3

So it compares 1st with 2nd, 3rd-4th, and so on. The folder always has even number of files.

Thanks a lot!

CodePudding user response:

Assuming the globing lists the files in the order you want:

declare -a list=( folder/* )

for (( i = 0; i < ${#list[@]}; i  = 2 )); do
  if [[ -f "${list[i]}" ]] && [[ -f "${list[i   1]}" ]]; then
    diff "${list[i]}" "${list[i   1]}" > "file_with_difference_$i"
  fi
done

CodePudding user response:

Assuming your filenames do not contain whitespace.

@Renaud has a great answer.

An alternative

printf '%s\n' * \
| paste - - \
| while read -r f1 f2; do
    diff "$f1" "$f2" > "diffs_$((  i))"
  done
  • Related