Shell scripts: determining filename length
Dave Ihnat
ignatz at dminet.com
Wed Sep 7 16:00:30 UTC 2005
On Wed, Sep 07, 2005 at 11:18:02AM -0400, Magnus Andersen wrote:
> I'd use the wc command with the -m flag to ge the number of charactes used
> in the file name. You could use an awk substr to mod the name if longer than
> 64.
I'd actually use "cut -d'.'" to get the filename and suffix.
Use "basename" if there's a chance there'll be a path prepended.
Then use the "wc -m" as recommended to determine string length.
(Actually, I don't see how "wc -m" is different than the traditional
"wc -c", but then, I just _wrote_ cut and paste...what do I know...hmm...
they took my name out of the latest man page???)
As to stripping the filename, well, "cut -c1-64" is a lot lighter
than awk. However, you have to worry about identical filenames in the
first 64 characters; I'd actually strip it down to something like 61
characters, and append a sequence number to guarantee uniqueness.
Something like:
COUNT=0;
MAXFNLEN=64;
CUTFNLEN=61;
cd $DESTDIR;
for FILE in *
do
FNAME=`echo $FILE | cut -d'.' -f1`;
FSUFF=`echo $FILE | cut -d'.' -f2`;
# If there is no suffix, cut will return the filename again
if [ "$FNAME" = "$FSUFF" ]
then
FSUFF="";
fi;
if [ `echo -n $FNAME | wc -c` -gt $MAXFNLEN ]
then
FNAME=`echo $FNAME | cut -c1-$CUTFNLEN``printf "%03d" $COUNT`;
let COUNT=$COUNT+1;
fi;
if [ "$FSUFF" ]
then
OUTFNAME=$FNAME.$FSUFF;
else
OUTFNAME=$FNAME;
fi;
<do whatever you're going to do with the filename here>
done;
Cheers,
--
Dave Ihnat
ignatz at dminet.com
More information about the redhat-list
mailing list