Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Length of filename

Status
Not open for further replies.

YYYYUU

Programmer
Dec 13, 2002
47
GB
I am using Korn Shell scripting for the following:

I am searching through a directory and getting all the filenames. if the file names have four characters before the extension, then I need to add an X to this to make five.

eg

FILE.txt would need to be FILEX.txt
but
FILES.txt would be fine.

So far

FILES=`ls *.txt 2>/dev/null`

for FILENAME in ${FILES}
do

SHORTNAME=`echo ${FILENAME} | cut -d"." -f1`

But I don't know how to get the length of SHORTNAME variable. Do I need to use awk? Can I use this with Korn Shell.

Please advise, thanks.
 
You could use the single character replacement the "?" to find file.txt
eg
FILES=`ls ????.txt 2>/dev/null`

for FILENAME in ${FILES}
do
SHORTNAME=`echo ${FILENAME} | cut -d"." -f1`
# To find Length of variable is ${#SHORTNAME} so
if [ ${#SHORTNAME} -ne 4 ];then
echo 'impossible !'
fi

HTH

Dickie Bird (:)-)))
 
The Korn shell has variable editing that's cleaner than piping variables to cut or awk. The following does the same thing...
[tt]
FILES=$(ls ????.txt 2>/dev/null)

for FILENAME in ${FILES}
do
NAMEPART=${FILENAME%.*}
EXTENSION=${FILENAME##*.}
NEWNAME=${NAMEPART}X.${EXTENSION}

if [[ -f ${NEWNAME} ]]
then
print -u2 "ERROR: ${NEWNAME} already exists!"
else
mv ${FILENAME} ${NEWNAME}
fi
done
[/tt]
Hope this helps!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top