George Thompson
George Thompson

Reputation: 7047

unix compare two directories if a directory exists in directory 1 only then do something

I have two directories, I would like to do something based on the results of a comparison.

Below is my script

#!/bin/sh
# the script doesn't work below if a the above line says bash
for i in $(\ls -d /data_vis/upload/); 
    do 
        diff ${i} /data_vis/upload1/;
    done

The output from the above script is

Common subdirectories: /data_vis/upload/2012_06 and /data_vis/upload1/2012_06
Common subdirectories: /data_vis/upload/2012_07 and /data_vis/upload1/2012_07
Only in data_vis/upload/: 2012_08
Only in /data_vis/upload/: 2012_09
Only in /data_vis/upload/: index.php
Only in /data_vis/upload/: index.php~

Question ?
How can I use this this output to do something e.g. see below

Pseudocode

if   Only in data_vis/upload/: 2012_08  # e.g if directory only exists in upload directory
    then do something
else 
    do something else
Finish

Any comments or better solutions/commands welcome!

Upvotes: 0

Views: 79

Answers (1)

Joerg Reinhardt
Joerg Reinhardt

Reputation: 358

I understood that You want to parse the output of the diff.

First, Your outermost for-loop is not necessary, since the "ls"-operation returns only one item. The task could be done as follows:

#!/bin/sh
diff data_vis/upload/ data_vis/upload1/ | while read line
  do
    if echo $line | grep "Only in">/dev/null;then
      # parse the name of the directory where the not matched dir is located
      dironlyin=$(echo $line|awk -F ":" '{split($1,f," ");print f[3];}');

      # parse the name of the not matched dir
      fileonlyin=$(echo $line|awk -F ":" '{l=length($2);print substr($2,2,l-2);}');

      # prove that the parsing worked correctly
      echo "do something with file \""$fileonlyin"\" in dir \""$dironlyin"\""
    else
      # do your own parsing here if needed
      echo "do something else with "\"$line\"
    fi
done

You need to do the parsing of the lines starting with "Common subdirectories" by yourself. I hope the awk mini-scripts can help You doing it!

Cheers Jörg

Upvotes: 1

Related Questions