how to rename all files that have a certain text in the filename using tcsh shell

Hello~

I'm on AIX version 5 and I believe I have the tcsh shell environment to play in. Can you guys help me with a solution to rename all files that have "eclp" in the filename to "ecl" ? I basically want to rename the files and strip the "p" out.

i.e. original filenames:

grp_eclp_grp_cent_ADTA.xlt grp_seri_grp_eclp_ADTB.xlt
grp_eclp_grp_cern_ADTA.xlt grp_seri_grp_eclp_ADTC.xlt
grp_eclp_grp_cern_ADTB.xlt grp_sftmd_grp_eclp_ADT.xlt

altered filenames when done:

grp_ecl_grp_cent_ADTA.xlt grp_seri_grp_ecl_ADTB.xlt
grp_ecl_grp_cern_ADTA.xlt grp_seri_grp_ecl_ADTC.xlt
grp_ecl_grp_cern_ADTB.xlt grp_sftmd_grp_ecl_ADT.xlt

Thanks in advance! :slight_smile:

Why you ask to use tcsh, if you have nothing ? Even your interactive command shell is tcsh, you can do your script using any shell which you have. And execute it even you use tcsh.

Example, I'm sure that you have sh in /bin directory, so this works, even it is ksh88 version or BourneShell - save this text to file rename.sh :

#!/bin/sh
#rename.sh
for f in $*
do
      newname=`echo "$f" | sed "s/^grp_eclp_/grp_ecl_/" `
      if [ "$newname" = "$f" ] ; then
           echo "no rename $f"
           continue
      fi
      echo "rename $f -> $newname"
      mv  "$f"  "$newname"
done

And after you have created file rename.sh , give execute priviledges and then call rename.sh with those files which you like to rename.

chmod a+rx rename.sh
./rename.sh  grp*ADTA*.xlt
# or
./rename.sh grp*.xlt
# or ...

Kshji,

Thanks for your help.

One of team members used the following (can you tell me what the difference is between your method and his?):

#!/usr/bin/sh

# usage: call ./rename.sh .*.xlt
for file in *.xlt
do
newfile=`echo $file | sed s/$1/$2/g`
echo is $newfile
mv $file $newfile
done

Both are almost perfect :).
My version use dynamic filenames, your teams dynamic replace rule.
Your team version not chech, is there name change or not. My version check it.

So this is the best:

#!/bin/sh
#rename.sh
# arg1=old string
# arg2=new string
# arg3-n = files to make name editing
old="$1"
new="$2"
# remove 2 args, rest are filenames
shift 2
for f in $*
do
      newname=`echo "$f" | sed "s/$old/$new/" `
      if [ "$newname" = "$f" ] ; then
           echo "no rename $f"
           continue
      fi
      echo "rename $f -> $newname"
      mv  "$f"  "$newname"
done

Using:

./rename.sh "grp_eclp_" "grp_ecl_"  grp*ADTA*.xlt