1832891 Members
2464 Online
110048 Solutions
New Discussion

change names of files

 
SOLVED
Go to solution
Rahul_13
Advisor

change names of files

Hi,

I have to write a script which will replace all the files starting with letter 'F' to letter 'G'.

Can anyone please help me.

Thanks,
Rahul
7 REPLIES 7
Steven E. Protter
Exalted Contributor

Re: change names of files

ls -1 | grep ^F > file
ls -1 | grep ^G >> file

while read -r rr
do
mv $rr $newname
done < file

You have to figure out what your renaming scheme is and make sure the variable $newname is filled.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Biswajit Tripathy
Honored Contributor
Solution

Re: change names of files

for file in F*
do
mv $file `echo $file | sed 's/^F/G/g'`
done

- Biswajit
:-)
A. Clay Stephenson
Acclaimed Contributor

Re: change names of files

Something like this:

#!/usr/bin/sh

cd to desired starting directory:

find . -type f -name 'F*' | while read X
do
BASE=$(echo "${X}" | cut -c 2-)
NEW="G${BASE}"
if [[ -f "${NEW}" ]]
then
echo "File ${NEW} exists; skipping" >&2
else
mv "${X}" "${NEW}"
fi
done

Note that this tests for the existence of the replaced file before doing the actual mv. I would replace the mv command with a harmless 'echo "Moving ${X} to ${NEW}"' command for testing before doing the real thing.
If it ain't broke, I can fix that.
Rahul_13
Advisor

Re: change names of files

Hi Steve,

My requirement in that if i have the following files say

File1
File2
File3

in a directory. It should look like

Gile1
Gile2
Gile3

after the script is executed. All the files starting with letter 'F' should start with letter 'G'.

Thanks,
Rahul
Biswajit Tripathy
Honored Contributor

Re: change names of files

That is exactly what the script in my last post will do.
If you want to do error checking, you probably have
to add a couple of lines to make sure that you are not
overwriting an existing file.

- Biswajit
:-)
harry d brown jr
Honored Contributor

Re: change names of files

cd toFdirectory

ls F* | xargs -i echo X{} {}|sed -e "s/ F/ G/g" -e "s/^X/mv /" | sh

live free or die
harry d brown jr
Live Free or Die
H.Merijn Brand (procura
Honored Contributor

Re: change names of files

# perl -MFile::Copy -e'for(){($g=$_)=~s/^F/G/;move$_,$g}'

# perl -e'map{($g=$_)=~s/^F/G/;`mv $_ $g}'

TIMTOWTDI

Enjoy, Have FUN! H.Merijn

Enjoy, Have FUN! H.Merijn