-1

I'm attempting to compare the name of a directory to a line in a text file. However even when the name of the directory and the line in the text file are the same I can't seem to get them to be "equal".

#!/bin/bash
for dir in /mnt/hgfs/VM/Command_for_Dozing_Logs/*/
do
    dir=${dir%*/}
    dir=${dir:(-10)}
    echo "Dir:$dir:"

    while read p; do
        echo "File:$p:"     
        if [ "$dir" == "$p" ]
        then
            echo "Variables are equal!"
        fi

    done </mnt/hgfs/VM/copiedFolders.txt
done

The folders I'm trying to match are in the Command_for_Dozing_Logs folder. The folders in it are:

2015.07.07
2015.07.08

My text file is like so:

2015.07.08
2015.05.23

So there should be at least one match, right? But no. I'm getting this as my output:

Dir:2015.07.07:
:ile:2015.07.08
:ile:2015.05.23
Dir:2015.07.08:
:ile:2015.07.08
:ile:2015.05.23

I'm really confused as to what's going on here. Why would that colon be replacing the first letter? How can I get the two variables to match?

codedude
  • 101
  • 1
    Your file has CR/NL or CR as line endings. Go back and edit it on a Linux/Unix system instead of Windows or Mac. – Chris Davies Jul 14 '15 at 13:21
  • I've never opened it in Windows. I created it in my Linux virtual machine. – codedude Jul 14 '15 at 13:22
  • OK I'll retract that part of my statement. Nevertheless the reason is (almost certainly) because there is CR at the end of each line in your file. tr -d '\015' < .../copiedFolders.txt > /tmp/fixed_copiedFolders.txt and then run it with /tmp/fixed_copiedFolders.txt instead. – Chris Davies Jul 14 '15 at 13:25
  • When I execute the script with a file with CR/NL line endings, I get exactly the same output as you do. With pure NL endings, everything works fine for me. – klimpergeist Jul 14 '15 at 13:25

1 Answers1

2

The reason for this is (almost certainly) because there is a CR character at the end of each line in your file. This is typical of files created on Windows and Mac systems; Linux/Unix-based systems use NL as the line ending character.

You can fix your file with this command, allowing you to use /tmp/fixed_copiedFolders.txt instead of the original.

tr -d '\015' < /mnt/hgfs/VM/copiedFolders.txt > /tmp/fixed_copiedFolders.txt

Alternative you can incorporate this into your script directly:

#!/bin/bash
for dir in /mnt/hgfs/VM/Command_for_Dozing_Logs/*/
do
    dir=${dir%*/}
    dir=${dir:(-10)}
    echo "Dir:$dir:"

    tr -d '\015' </mnt/hgfs/VM/copiedFolders.txt |
        while read p; do
            echo "File:$p:"     
            if [ "$dir" == "$p" ]
            then
                echo "Variables are equal!"
            fi
        done
done
Chris Davies
  • 116,213
  • 16
  • 160
  • 287