Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Using "find" in while loop is giving blank results with input from DOS text file

I have a text file that contains a list of file names without the folder path or extension. I want to loop over this file and find the path that matches the file name. However, my find command inside the while loop is not giving me the result. The find command works when I take it out of the while loop.

Here is my example input file (input.txt):

12345
56789
...
09987
89008

The actual files are stored like this:

/home/user/path/to/file/12345.jpg

Here is my script (find_files.sh):

#!/bin/bash
while IFS= read -r line || [[ -n "$line" ]]; do
    echo $line
    file=$(find /home/engage/ -name "${line}*" -print)
    echo $file
done < "$1"

And I'm calling it with:

./find_files.sh input.txt

The output I'm getting is this:

12345

56789
...
09987

89008

So find is not getting any results. What am I doing wrong? Thanks!

like image 201
Drew S Avatar asked Nov 21 '25 21:11

Drew S


1 Answers

Your input file has Windows style \r\n line endings, and the unexpected \r is causing the match to fail.

Delete them from your input file with dos2unix, fromdos or tr -d '\r' < input.txt > fixed_input.txt.

You can alternatively strip them at run time in your loop with line=${line%$'\r'}

like image 164
that other guy Avatar answered Nov 23 '25 12:11

that other guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!