1850127 Members
3650 Online
104050 Solutions
New Discussion

Re: converting filenames

 
SOLVED
Go to solution
Pando
Regular Advisor

converting filenames

dear gurus,

i have 2 inquiries.

1. is it possible to convert the filename from lowercase to uppercase? Is this possible using awk or sed or perl?

2. i have a filename with the following pattern.

AAA_BB_20Jul2006_1234.TXT

is it possible to rename it using awk, perl or sed to:

AAA-BB_20Jul2006_1234.TXT?

Maximum points to all correct answers.
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor

Re: converting filenames

1) yes, yes, and yes.

However an easier approach is to use tr.

#!/usr/bin/sh

typeset OLD_FNAME=""
typeset NEW_FNAME=""
typeset -i STAT=0
while [[ ${#} -ge 1 ]]
do
OLD_FNAME=${1}
shift
if [[ -r "${FNAME}" ]] # file exists
then
NEW_FNAME=$(echo "${OLD_FNAME}" | tr "[a-z]" "[A-Z]")
if [[ "${NEW_FNAME}" != "${OLD_FNAME}" ]]
then
if [[ -r "${NEW_FNAME}" ]]
then
echo "${NEW_FNAME} already exists." >&2
else
mv "${OLD_FNAME}" "${NEW_FNAME}"
STAT=${?}
fi
fi
else
echo "${OLD_FNAME} not found." >&2
fi
done
exit ${STAT}
----------------------------------

Your second question is exactly the same except:

NEW_FNAME=$(echo "${OLD_FNAME}" | tr "[a-z]" "[A-Z]")
becomes:

NEW_FNAME=$(echo "${OLD_FNAME}" | tr "-" "_")


Use it like: myscript.sh filename1 filename2 ...
If it ain't broke, I can fix that.
Hein van den Heuvel
Honored Contributor
Solution

Re: converting filenames

Using perl...

1.

perl -e '$old=shift @ARGV; rename $old, uc($old)' test.tmp

2.

perl -e '$old=shift @ARGV; $_ = $old; s/-/_/; rename $old, $_' a-b.tmp


fwiw,
Hein.




Sandman!
Honored Contributor

Re: converting filenames

>convert the filename from lowercase to uppercase?

# ls -1 | awk '{system("mv "$0" "toupper($0))}'

>2. from...AAA_BB_20Jul2006_1234.TXT
to...AAA-BB_20Jul2006_1234.TXT

# ls -1 | awk '{x=$0;sub("_","-");system("mv "x" "$0)}'
Pando
Regular Advisor

Re: converting filenames


Hi Hein,

What do you mean by the $old in the perl command line?

Could you explain it to me?

Thanks!
Hein van den Heuvel
Honored Contributor

Re: converting filenames

>> perl -e '$old=shift @ARGV; rename $old, uc($old)' test.tmp

The top structure here is:
perl -e 'blah blah' argument(s)

So $old is not on the command line, but within the 'one-liner' program 'blah blah'.

The $old variable in the program is picked up from the first argument passed: the file name to be changed.
I just used a 'shift @ARGV' to get the value.
That's your first argument for the rename.
The second argument is the un-named 'new' name computed as uppercase on $old using uc($old).

Clear?
Hein.