Issue
My task is easy enough to accomplish in python, but I am trying to do it with a Bash script.
I have files named [0001-9999].jpg
(i.e, always 4 digits long; e.g, 0003.jpg
, 4003.jpg
) in two different directories,
'left' & 'right' (corresponding to left and right-page bindings of a scanned book). I want to combine the two directories, in ascending order such that they are named [1-19998].jpg
in a new 'output' directory.
I am stuck at getting my Bash script to recreate the filename format (always 4-digits, ranging from 0001 to 9999) so that I can cp
them to 'output'.
Here is what I have so far in combine.sh
:
#!/bin/bash
# combine.sh assumes it is copied into intended directory, and all files are in order and present.
# verso (left page) folder is called 'left', recto (right page) folder is called 'right'.
# first (and only) argument should be the word 'left' or 'right' in lower-caps, for first page.
# get total number of pages
l=`ls -l left | wc -l`
r=`ls -l right | wc -l`
size=$(( ($l - 1) + ($r - 1) ))
# set $first offset based on input
if [ "$1" == "left" ]
then
first=0
elif [ "$1" == "right" ]
then
first=1
else
echo invalid first
fi
# loop to copy files
j=1
for (( i=1 ; i<=$size; i++ ));
do
# alternate between left and right, starting w/ $1
# copying into ./output/ with new name [i].jpg
dir=$(( (i + 1 + first) % 2 )) # offset for left or right
if [ $dir -eq 0 ]
then
echo should be 000$j.jpg
# move/copy next jpg of verso dir into combined dir
elif [ $dir -eq 1 ]
then
(( j += 1 ))
# move/copy next jpg of recto dir into combined dir
fi
done
Clearly, my current model wouldn't work past 0009.jpg
. It is the last piece of this script (just need to cp
after) though, and any help would be greatly appreciated! I'm guessing I need to do some awk
-ing on the input filename strings?
Solution
You're looking for something like this:
case $1 in
left) dir2=right ;;
right) dir2=left ;;
*) # TODO handle bad argument
esac
dir1=$1
n=0
for src1 in "$dir1"/*.jpg; do
echo mv "$src1" "output/$((n+=1)).jpg"
src2=$dir2${src1#"$dir1"}
if test -e "$src2"; then
echo mv "$src2" "output/$((n+=1)).jpg"
else
break
fi
done
Remove echo
s if the output looks good.
Answered By - oguz ismail Answer Checked By - Senaida (WPSolving Volunteer)