Help Dynamic looping based on files

Hi I have to run the script (a part of the code) in a loop for the no of times the files present in the directory, by taking one file and process and next another file.

For example, if we do ls and the result have:

$ls
abc.dat   def.dat   ghi.dat

The script code should loop for 3 times by taking abc.dat and process and next def.dat and then ghi.dat for processing.

Like this if we have 10 files, it should loop 10 times.

PS: Here the file names will change time to time, but the extensions are same (.dat).

Have you tried this:

ls -1 *.dat | \
while read fname
do
     echo "Current file is: [${fname}]."
done
# Or you can use "find"
find . -name "*.dat" -type f | \
while read fname
do
     echo "Current file is: [${fname}]."
done
1 Like

try this

for filename in `find .  -type f -name "*.dat" -exec ls -1 {} \; | sed 's/\.\///'`
do
echo $filename
done

That's a dangerous use of backticks and wholly unnecessary.

find .  -type f -name "*.dat" -exec ls -1 {} \; | sed 's/\.\///' | while read LINE
do
        echo "$LINE"
done

If you have GNU "find" and you only need the filename (without path), you can use:

find . -name "*.dat" -type f -printf "%f\n" | \
while read fname
do
     echo "Current file is: [${fname}]."
done