Read filenames in sorted order

Hi ,
My requirement is to scan a directory for file names with LTR.PDF*
and send those files via ftp to another server one by one.

Now the the problem is file names are like LTR.PDF ,LTR.PDF1 ,LTR.PDF2.....LTR.PDF10..upto 99
and these needs to be sent in sorted order.
is there a way to get the files in sorted order based on file names in for loop

for file in $BASEDIR/output/$LTRNAMELTR.PDF*
do
# The following check is necessary; if no files end with ltr*.afp
# then $file will be assigned "ltr*.afp"
if [ ! -f $file ]
then
echo " No print LTR PDF File created"
break
fi
FILENAME=${file%%.afp}
BASEFILENAME=$( basename $FILENAME )
ftp.......
done

quick reponse wil be much appreciated..thanks

i guess, -1 (numeric one) in ls command will give sorted order

ls -1 *.afp

thanks for the quick reply..am pretty new to unix scripts...
how to redirect the output of ls -1 into for loop or to any othe looping construct

Are you sure? This indeed will give sorted order but on Strings.
Hence,

eon.1, eon.2, eon.3, eon.10, eon.11, eon.99 etc, when passed thru ls -1, the output would be:

 
eon.1 
eon.10
eon.11
eon.2
eon.3
eon.99

So the above won't work in the current query.

 
$ ls -1 | sort -tF -k2 -n
LTR.PDF
LTR.PDF1
LTR.PDF2
LTR.PDF10
LTR.PDF11
LTR.PDF20

 
ls -1 | sort -tF -k2 -n | while read file
do
# your if condition
# your ftp code
done
2 Likes

Try this:

[[ Assumption : basename of the file will remain the same. Only the sequence number will change ]]

 
for i in ' ' $(seq 1 99); do                        # Please include ' ' as this will give you .pdf without any numbering in them which I guess you want to include as well
   MYFILE=$LTRNAMELTR.PDF${i}
   if [[ -f ${MYFILE} ]]; then
      <<Do Your Stuff Here with this file>>
   else
       continue 
   fi
done

---------- Post updated at 04:06 PM ---------- Previous update was at 04:03 PM ----------

I thought of this one, but this will fail if file path or name contains more than 1 dot '.' :slight_smile:

1 Like

yes.. but seems his requirement is

My requirement is to scan a directory for file names with LTR.PDF*

I agree... :slight_smile:

Yupp that is true... :b:

thanks guys....didn't expect would get solution within minutes!!!

Just to clarify that the ASCIIbetical order is part of the shell expansion ( *.afp , in this case) and not the -1 (one file per line) option.
Note also that -1 option is active only in interactive usage ( ls -1 | ... doesn't make sense because it's equivalent to ls | ... ).

I would write something like this [1]:

printf '%s\n' LTR.PDF* |
  sort -t. -k2.4n |
    while IFS= read -r; do
      <process "$REPLY" here ...>
    done

[1] Older shells won't accept read with no argument(s) (and some don't provide the -r option), so you may need to use:

while IFS= read fname; do
  <process "$fname" here ...>
done