1748265 Members
3990 Online
108760 Solutions
New Discussion юеВ

Re: Help in script

 
SOLVED
Go to solution
Waqar Razi
Regular Advisor

Help in script

I need to write a script which renames the files starting with XM and just take XM off their resulting names. For example, lets say there is a file called XMtest1.txt. The script will take XM off and rename this file to test1.txt and places it in the same working directory.

Any help will be highly appreciated.
3 REPLIES 3
Patrick Wallek
Honored Contributor
Solution

Re: Help in script

Try this:

#!/usr/bin/sh
for NAME in XM*.txt
do
NEWNAME=$(echo ${NAME} | sed 's/^SM//g')
echo "${NAME} -- ${NEWNAME}"
mv ${NAME} ${NEWNAME}
done
R.K. #
Honored Contributor

Re: Help in script

Hi Waqar,

You can also try this:

#!/usr/bin/sh
for FILE in `ll XM* | awk '{print$9}' | cut -c 3-`
do
mv XM${FILE} ${FILE}
done
Don't fix what ain't broke
Dennis Handly
Acclaimed Contributor

Re: Help in script

>R.K.: You can also try this:
for FILE in `ll XM* | awk '{print$9}' | cut -c 3-`

There is no need to use ll(1) vs ls(1). The former is going to make the disk and NFS sweat by statting each file, you just want the name.

If you are already using awk, no need to use cut(1).

And you can improve on Patrick's sed by using a shell builtin:
for NAME in XM*; do
NEWNAME=${NAME#XM}
echo "${NAME} -- ${NEWNAME}"
mv ${NAME} ${NEWNAME}
done

If there is a chance there are no XM* files, you can do:
for NAME in $(ls XM* 2> /dev/null); do
NEWNAME=${NAME#XM}
echo "${NAME} -- ${NEWNAME}"
mv ${NAME} ${NEWNAME}
done

Or just add:
if [ "$NAME" = "XM*" ]; then break; fi