HPE Community read-only access December 15, 2018
This is a maintenance upgrade. You will be able to read articles and posts, but not post or reply.
Hours:
Dec 15, 4:00 am to 10:00 am UTC
Dec 14, 10:00 pm CST to Dec 15, 4:00 am CST
Dec 14, 8:00 pm PST to Dec 15, 2:00 am PST
cancel
Showing results for 
Search instead for 
Did you mean: 

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
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

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