Operating System - HP-UX
1839589 Members
2402 Online
110151 Solutions
New Discussion

shell script to copy and change the pattern of the filename

 
Padmaja_1
New Member

shell script to copy and change the pattern of the filename

I 'm new to shell scripting . I would like to do the following . There are 2 files in a directory like
2003_4_56_20:1:test.txt, 2003_10_23_16:1:2_test.txt. I would like all the colons to change to underscore, ie for 2003_4_56_20:1:test.txt it should be 2003_4_56_20_1_test.txt . The original file should not be overwritten, only the filename has to change. How do I go about doing this?

John
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor

Re: shell script to copy and change the pattern of the filename

ls | while read OLDNAME
do
NEWNAME=$(echo "${OLDNAME}" | tr ":" "_")
if [[ "${NEWNAME}" != "${OLDNAME}" ]]
then
mv ${OLDNAME} ${NEWNAME}
fi
done
If it ain't broke, I can fix that.
Rodney Hills
Honored Contributor

Re: shell script to copy and change the pattern of the filename

How about-

#!/usr/bin/ksh
for x in *:* ; do
y=`echo $x | sed -e 's/:/_/g'`
if [[ -a $y ]] ; then
echo "not renaming $x - new name already exists"
exit
fi
mv "$x" "$y"
done

HTH

-- Rod Hills
There be dragons...
Ulrich Deiters
Frequent Advisor

Re: shell script to copy and change the pattern of the filename

The attached script renames all files in a directory whose names match a given pattern (even one including blanks). In your case you might use something like

rename ".*:.*" "s/:/_/g"

to select all files with a colon in their name and to replace all colons by underscores.