如何使用Bash在文件夹中获取.png文件数组

Alo*_*los 4 linux bash

嗨,我是bash编程的新手,需要一些帮助.我正在构建一个用于图像处理的管道.我希望能够将png图像放在一个文件夹中并将它们传递给clusterImage.pl一旦完成,我想将输出的文件传递给seperateObjects.pl,输出的文件具有相同的名称但具有kmeansOutput. all.matrix附在最后.以下是我到目前为止所做的,但它不起作用.任何帮助将不胜感激.谢谢

#!/bin/bash
#This script will take in an image and a matrix file.
#The output will be an image and a matrix file.

list=`ls *.png`
for i in $list
do
$file="./$list"
$image_array = $list
echo $file
#Cheching to see if the file exists.
for((j=0;j<=i;j++))
do
if [ -e image_array[j] ]; then
echo $file
echo "Begining processing"
#Take in an image and create a matrix from it.
perl clusterImage.pl SampleImage.png
#Take in a matrix and draw a picture showing the centers of all
#of the colonies.
perl seperateObjects.pl SampleImage.png.kmeansOutput.all.matrix
echo "Ending processing"
else
echo "There is an issue"
fi
done
done
Run Code Online (Sandbox Code Playgroud)

kni*_*ttl 7

这应该工作:

for file in *.png; do
    # do stuff with your file:
    perl clusterImage.pl "$file";
    # …
done
Run Code Online (Sandbox Code Playgroud)


Dav*_*d Z 4

我发现您的代码存在一些问题(或潜在的改进):

  1. 您不需要循环,for i in $list因为您从不在脚本中使用$i- 这会导致一遍又一遍地执行相同的操作(与.png目录中的文件数量相同的次数)
  2. 您不需要使用 Bash 数组,因为 Bash 可以迭代列表中的不同文件名,例如*.png.
  3. 我怀疑您的意思是在目录中的perl clusterImage.pl每个文件上运行...或者是吗?.png这有点很难说。编辑您的问题以更清楚地解释您的意思,我可以相应地编辑我的答案。
  4. 您可以使用他们所说的短路来代替语句if[ -f file.png ] && echo "file exists"短于

    if [ -f file.png ]; then
        echo "file exists"
    fi
    
    Run Code Online (Sandbox Code Playgroud)

如果我明白你想要做什么(我不确定我明白),我认为这可能对你有用。对于目录中的每个图像,这将运行perl clusterImage.pl <name_of_image.png>并且perl separateObjects.pl <name_of_image.png>.kmeansOutput.all.matrix.

for image in *.png
do
  [[ -f $image ]] && perl clusterImage.pl $image && perl separateObjects.pl $image.kmeansOutput.all.matrix
done
Run Code Online (Sandbox Code Playgroud)