Bash – Loop in text files shell script

bashshell-script

I have a list of files in one directory and a set of jpegs corresponding to each file in another directory. I need to loop over all files, and for each file name, determine the target directory.

For example, if I have three text files called foo.txt, bar.txt and baz.txt in /home/userA/folder/, the corresponding jpegs will be in /home/userA/folder2/foo/, /home/userA/folder2/bar/ and /home/userA/folder2/baz/.

I wrote a script that should loop over all txt files and get the corresponding target directories but it's giving me an error:

bash: /home/userA/folder/File1.txt: syntax error: operand expected (error token is "/home/userA/folder/File1.txt")`

My script:

#!/bin/bash
FILES=/home/userA/folder/*.txt
for i in $FILES
do
    str1=$i | cut -d'/' -f5 #to get the name of the file
    echo /home/userA/folder2/$i_filename #I want to include the .txt filename in the output to be like this /home/userA/folder2/Text1_filename    
done

How can I fix this?

Best Answer

Using find:

#!/bin/bash
path="/home/userA/folder"
find "$path" -maxdepth 1 -type f -name "*.txt" -print0 | while read -d $'\0' file; do
    a="$path/$(basename $file)/a_%06.jpg"
    echo "$a
done
Related Question