I'd like to create a string array from a long directory listing, extracting only files last modified on a specific date (e.g. Aug 08). I tried the following:
aug8=`ls -ltr |grep 'Aug 08'`
The result was an array (I think) but all of the output from the listing went to the first element of the array, so that:
echo ${aug8[0]}
displayed everything and:
echo ${aug8[1]}
displayed nothing.
Any suggestions as to how I can get each filename in the directory listing to be a single element in the "a8" array?
The reason why your command failed was that the shell was not aware that "aug8" should be an array. That you found the output of "ls" in aug8[0] was just because for every variable this is the case:
willy="x"
print - $willy[0] # will yield "x"
If you want to assign the content to an array you would have to use the "set -A" subcommand in the shell. Alas, the output of "ls -ltr" contains not only the filenames but also a lot of other information which is why it will have to be trimmed before. I have not Unix-system at hand writing this, but it would be something like the following:
set -A aug8 "$(ls -ltr | sed -n '/Aug 08/ s/ */ /gp' | cut -d' ' -f12)"
There are two problems with this approach anyways: first, while evaluating the commandline the subshell will be executed and the command be replaced by its output. UNIX-commandlines have a maximum length (4096 characters) which could be exceeded if there are enough files with long enough names.
Secondly, ksh-arrays have a maximum number of elements, which is 1024. This might be not enough if the directory contains enough matching files (although presumably the other limit would be hit first).
The first limitation could be circumvented by using a loop to assign the array elements:
(( iCnt=0 ))
ls -ltr | sed -n '/Aug 08/ s/ */ /gp' | cut -d' ' -f12 | while read filename ; do
aug8[$iCnt]="$filename"
(( iCnt += 1 ))
done
But the second limitation cannot be overcome: arrays cannot exceed 1024 elements. Still i cannot understand what it would be necessary to create the array in first place. If you want to process these files one after the other apply the logic from my second example and instead of assigning the content of variable $filename to an array element do some processing with it:
ls -ltr | sed -n '/Aug 08/ s/ */ /gp' | cut -d' ' -f12 | while read filename ; do
do_something "$filename"
done