Operating System - HP-UX
1834771 Members
3195 Online
110070 Solutions
New Discussion

Re: Need help writing a shell script

 
SOLVED
Go to solution
sanman_2
Occasional Contributor

Need help writing a shell script

please help me with this!!

I need to write a shell script that removes the characters given as the second argument from the end of the name of the file given as the first argument. So memo1.sv should rename memo1.sv to memo1.

Thanks for all your kind help!!!!
5 REPLIES 5
John Palmer
Honored Contributor

Re: Need help writing a shell script

Hi,

A simple script with no error checking follows:-

#!/usr/bin/sh

FILE=${1}
SUFFIX=${2}
NEWFILE=${FILE%${SUFFIX}}

mv ${FILE} ${NEWFILE}
exit

Call it with:-

<scriptname>

Regards,
John
Kofi ARTHIABAH
Honored Contributor

Re: Need help writing a shell script

Try this:

#!/bin/sh
#
# renames without the last extension.

OLDNAME=$1
NEWNAME=` echo $OLDNAME | awk '{ n=split($1,filen,".")
for (i = 1; i < n ; i++ ) printf filen[i]"." }'`
mv $OLDNAME $NEWNAME

nothing wrong with me that a few lines of code cannot fix!
Rainer_1
Honored Contributor
Solution

Re: Need help writing a shell script

#!/sbin/sh
mv $1 $(basename $1 .$2)

call it with ie

<script> file.ext ext
Rainer_1
Honored Contributor

Re: Need help writing a shell script

to rename a file with an arbitary extension

#/sbin/sh
mv $1 $(echo $1|sed 's/\(.*\)\..*$/\1/')
Tommy Palo
Trusted Contributor

Re: Need help writing a shell script

If you want to do it for any filename recursively:

#!/usr/bin/ksh
if [ $# = 0 ]; then
echo "Arg: fileSuffix"
exit
fi
MV=/tmp/mvSuff
echo 'mv $1 $(dirname $1)/$(basename $1 .'"$1"')' > $MV
chmod +x $MV
find . -name "*.$1" -exec $MV {} \;
rm $MV
Keep it simple