Bash - open an image only if there is a corresponding text file

I ran into a problem in Bash when I tried to open images only based on the information stored in .txt files. I am trying to sort several images by size or height and display the image with them in sorted order, but if there is a .jpg in the folder in the file without the .txt file with the same name, it should not process it.

I have part of sorting my situation, and I'm trying to figure out how I would like to open only images with the .jpg extension with the .txt file.

I decided that the solution would look like I put every .jpg name (without extension) in a list, and then process the list and run something like:

[if -f $ filename.txt]; then ~~~

but I ran into the iteration problem without a for loop, or all snapshots will open multiple times. My attempt:

for i in *jpg; do
y=$y ${i.jpg}
done
if[ -f $y.txt ] then
(sorting parts)

This looked only at the last file name in y, as it should be, but I'm trying to figure out a way to look at each individual file name and see if this text file exists to include it in the sort.

Many thanks for your help!

+4
source share
2 answers

Collecting a list of file names in one variable is antipattern. You want to collect them in an array instead.

a=()
for f in *.jpg; do
    if [ -e "${f%.jpg}".txt ]; then
        continue
    fi
    a+=("$f")
done
# now do things with "${a[@]}"

Often you do not need to collect files in an array - just do everything you do inside the loop forfor each individual file when moving files.

( y=$y ${i%.jpg} y - y i .jpg, , , .)

+1

, . jpg, txt:

find . -name "*.jpg" -maxdepth 1 -exec /bin/bash -c '[ -e "${0%.*}.txt" ] && echo "$0";' {} \;
0

Source: https://habr.com/ru/post/1656491/


All Articles