How To: Rename A File In Bash

by on January 27, 2009 · 3 comments· LAST UPDATED March 7, 2010

in , ,

How do I rename a file in bash under UNIX / OS X / Linux / BSD operating systems?

The mv command rename SOURCE file to DESTINATION file using the following syntax:

mv oldname newname
mv source dest
mv olddir newdi

Task: Rename A File Called /tmp/foo To /tmp/bar

Type the following command (open terminal and issue the following commands):

# create /tmp/foo 
touch /tmp/foo
ls -l /tmp/foo
mv /tmp/foo /tmp/bar
ls -l /tmp/bar
ls -l /tmp/foo

Task: Rename A Directory Called offfer To offers

Type the following command:

mv offfer offers

Task: Prompt Before Overwrite

The -i option is interactively file processing option. You get an error message before moving a file that would overwrite an existing file. If the response from the user begins with the character y or Y, the move / rename is attempted.

touch /tmp/test
mv -i /tmp/test /tmp/ba

Sample outputs:

mv: overwrite `/tmp/bar'? y

The -u Option

The -u option move only when the SOURCE file is newer than the destination file or when the destination file is missing:

mv -u data.txt /mnt/floppy/backup.txt

The -v Option

The -v option explain what is being done:

mv -v /tmp/bar /tmp/output.txt

Sample outputs:

`/tmp/bar' -> `/tmp/output.txt'

Task: Rename multiple files

Use rename command renames multiple files. For example rename all *.perl file as *.pl, enter:

 
rename .perl .pl *.perl
 

See howto rename multiple files at a shell prompt for further details.

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 3 comments… read them below or add one }

1 Philippe Petrinko March 6, 2010 at 9:59 pm

typo here:
ename .perl .pl *.perl
instead of
rename

Reply

2 Other 1 Philippe December 19, 2013 at 6:24 am

I do not see any typo here.

Reply

3 Other 1 Philippe December 19, 2013 at 6:25 am

Ah, never mind. I see last updated date at the top of the page. You can delete this comment.

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , , , , , ,

Previous Faq:

Next Faq: