2

I have 100 folders inside every folder I have one or two files named as the following:

XXX_001_014_max.jpg
XXX_001_024_max.jpg

I saved the folders names in a file "list.txt"

I ran the following code to rename the files inside the folders at once:

#!/bin/bash
for i in $(cat list.txt); do
mv ${i}/XXX_001_014_max.jpg ${i}/image.jpg
done

I aim to rename only the file XXX_001_014_max.jpg to image.jpg and if this file does not exist(i.e. I have only one file inside the folder), then I want the code to rename the second file XXX_001_024_max.jpg to image.jpg

I know how to rename the files using the command mv but I am not familiar with the exact usage of if statement in this case.

1

Avoid the for i in $(cat squeeze) construct - it will fail if any of your directory names contains IFS characters...
I would read the lines into an array and then simply rename the first file in each directory. Since you always have one or two files in each directory, that means renaming the first one in each directory should do the job - e.g. with bash:

mapfile -t mylist <list.txt
for i in "${mylist[@]}"
do
set -- "$i"/*
echo mv -- "$1" "$i"/image.jpg
done
set --

Remove the echo if you're happy with the result.

1
if [ -f XXX_001_014_max.jpg ]
then
  SOURCE=XXX_001_014_max.jpg
else
  SOURCE=XXX_001_024_max.jpg
fi
mv $SOURCE image.jpg
1
if [ -f XXX_001_014_max.jpg ] 
then
    mv XXX_001_014_max.jpg image.jpg
else 
    mv XXX_001_024_max.jpg image.jpg
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy