Alex Raj Kaliamoorthy Alex Raj Kaliamoorthy - 6 months ago 21
Bash Question

How to assign all the files listed in a directory to a filelist using shell script?

I have a requirement to compare files available in a directory and the below code is working fine only when I mention the file names (file1 file2 file3 file4) individually to the filelist

#!/bin/bash

filelist=(file1 file2 file3 file4)


# Outer for loop
for (( i=0; i<${#filelist[@]} ; i+=1 )) ; do
# Inner for loop
for (( j=i+1; j<${#filelist[@]} ; j+=1 )) ; do

echo "Unique between ${filelist[i]}" "${filelist[j]}" > unique${filelist[i]}${filelist[j]}.txt

echo -e "Unique in ${filelist[i]}" >> unique${filelist[i]}${filelist[j]}.txt

# Will produce unique lines in 'file i' when comparing 'file i' and 'file j'
join -v 1 <(sort ${filelist[i]}) <(sort ${filelist[j]}) >> unique${filelist[i]}${filelist[j]}.txt

echo -e "Unique in ${filelist[j]}" >> unique${filelist[i]}${filelist[j]}.txt

# Will produce unique lines in 'file j' when comparing 'file i' and 'file j'
join -v 2 <(sort ${filelist[i]}) <(sort ${filelist[j]}) >> unique${filelist[i]}${filelist[j]}.txt

done

done


But what exactly I want is to assign the files that are available in a directory to the filelist directly. Any working solution please?

Answer

try this code:

 #!/bin/bash

#set basedir to . if no dir is given
if [ -n "$1" ]; then basedir=$1; else basedir=$(pwd);fi

filelist=($(/bin/ls $basedir))
# Outer for loop
for (( i=0; i<${#filelist[@]} ; i+=1 )) ; do
    # Inner for loop
    for (( j=i+1; j<${#filelist[@]} ; j+=1 )) ; do

    echo "Unique between $basedir/${filelist[i]}" "$basedir${filelist[j]}" > $basedir/unique${filelist[i]}${filelist[j]}.txt

    echo -e "Unique in $basedir/${filelist[i]}"  >> $basedir/unique${filelist[i]}${filelist[j]}.txt

    # Will produce unique lines in 'file i' when comparing 'file i' and 'file j'
    join -v 1 <(sort $basedir/${filelist[i]}) <(sort $basedir/${filelist[j]}) >> $basedir/unique${filelist[i]}${filelist[j]}.txt

    echo -e "Unique in  $basedir/${filelist[j]}" >> $basedir/unique${filelist[i]}${filelist[j]}.txt

    # Will produce unique lines in 'file j' when comparing 'file i' and 'file j'
    join -v 2 <(sort $basedir/${filelist[i]}) <(sort $basedir/${filelist[j]}) >> $basedir/unique${filelist[i]}${filelist[j]}.txt

    done

done

The folder should not contain directories. But its working ether. The unique files will created in folder given to the script.

Comments