How to move or rename a file in linux?

mv (short form for move) command is the linux command used to move a file from one location to another. Just like moving the file location, mv can move file names from one name to another. i.e with mv command can be used to rename a file. The syntax for mv command is as follows


mv source destination
mv [options] sourcefile /path/to/destination_directory
mv [options] /path/to/source_directory /path/to/destination_directory
mv [options] filename newfilename
mv [options] /path/to/filename /path/to/newfilename


Some important options
  • -i (interactive) : prompt before overwrite
  • -n : no overwriting of existing files.
  • -f (force) : force overwriting the destination
  • -v (verbose) : Explains what is being done

Examples

To move a file from current directory to my home directory
mv file.txt /home/calypso/

To rename a file abc.txt to xyz.txt

mv abc.txt xyz.txt
To move a file README.txt from current location to my home directory and change the name to README_old.txt, type
mv README.txt /home/calypso/README_old.txt
To rename a directory named monday in my home directory to tuesday
mv /home/calypso/monday /home/calypso/tuesday
To move all .txt filesin current directory toanother  directory  Documents located in the current directory

mv *.txt Documents/
To move everything from the current directory /home/calypso/Misc except file1.txt
mv !(file1.txt) /home/calypso/Misc/
To move everything from the current directory /home/calypso/Misc except file1.txt and file2.txt

mv !(file1.txt|file2.txt) /home/calypso/Misc/
For more details on mv command see the man pages

Comments

  1. To exclude files while mv command was new to me.thanks

    ReplyDelete
    Replies
    1. Some times excluding files with ! (exclamation) symbol might not work and you may get an error

      -bash: !: event not found

      This occurs because extglob option is disabled in your bash shell. To enable it, use the command

      shopt -sq extglob

      To enable it permanently add the above command to /etc/bashrc

      Delete

Post a Comment

Popular posts from this blog

Understanding awk command with examples

Understanding sed command with example -Part 1

How to install a Software in Linux