Letysite.ru

IT Новости с интернет пространства
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Linux move file

How to Move Files and Directories in Linux (mv Command)

Updated Oct 8, 2019

Moving files and directories is one of the most basic tasks you often need to perform on a Linux system.

In this tutorial, we will explain how to use the mv command to move files and directories.

How to Use the mv Command #

The mv command (short from move) is used to rename and move and files and directories from one location to another. The syntax for the mv command is as follows:

The SOURCE can be one, or more files or directories, and DESTINATION can be a single file or directory.

  • When multiple files or directories are given as a SOURCE , the DESTINATION must be a directory. In this case, the SOURCE files are moved to the target directory.
  • If you specify a single file as SOURCE , and the DESTINATION target is an existing directory, then the file is moved to the specified directory.
  • If you specify a single file as SOURCE , and a single file as DESTINATION target then you’re renaming the file.
  • When the SOURCE is a directory and DESTINATION doesn’t exist, SOURCE will be renamed to DESTINATION . Otherwise if DESTINATION exist, it be moved inside the DESTINATION directory.

To move a file or directory, you need to have write permissions on both SOURCE and DESTINATION . Otherwise, you will receive a permission denied error.

For example, to move the file file1 from the current working directory to the /tmp directory you would run:

To rename a file you need to specify the destination file name:

The syntax for moving directories is the same as when moving files. In the following example, if the dir2 directory exists, the command will move dir1 inside dir2 . If dir2 doesn’t exist, dir1 will be renamed to dir2 :

Moving Multiple Files and Directories #

To move multiple files and directories, specify the files you want to move as the source. For example, to move the files file1 and file2 to the dir1 directory you would type:

The mv command also allows you to use pattern matching. For example, to move all pdf files from the current directory to the

/Documents directory, you would use:

mv Command Options #

The mv command accepts several options that affect default command behavior.

In some Linux distributions, mv may be an alias to the mv command with a custom set of options. For example, in CentOS mv is an alias to mv -i . You can find whether mv is an alias using the type command:

If mv is alias the output will look something like this:

If conflicting options are given, the last one takes precedence.

Prompt before overwriting #

By default, if the destination file exists, it will be overwritten. To prompt for confirmation, use the -i option:

To overwrite the file type y or Y .

Force overwriting #

If you try to overwrite a read-only file, the mv command will prompt you whether you want to overwrite the file:

To avoid being prompted use the -f options:

This option is especially useful when you need to overwrite multiple read-only files.

Do not overwrite existing files #

The -n option tells mv never to overwrite any existing file:

If a file1 exists the command above will do nothing. Otherwise it will move the file to the /tmp directory.

Backing up files #

If the destination file exists you can create a backup of it using the -b option:

The backup file will have the same name as the original file with a tilde (

Use the ls command to verify that the backup was created:

Verbose output #

Another option that can be useful is -v . When this option is used, the command prints the name of each moved file:

Conclusion #

The mv command is used to move and rename files and directories.

For more information about the mv command, check the man page or type man mv in your terminal.

New Linux users who are intimidated by the command line can use the GUI file manager to move their files.

If you have any questions or feedback, feel free to leave a comment.

Команда mv

Описание команды mv

Команда mv используется для перемещения одного или нескольких файлов (или директорий) в другую директорию, а также для переименования файлов и директорий.

Синтаксис

исходные_файлы — это то, что мы будем перемещать или переименовывать. То есть это либо один файл, либо несколько файлов, либо директория, либо несколько директорий.

куда — это название директории, в которую мы перемещаем исходные файлы или директории. Или же это новое название файла или директории, если выполняется переименование. То есть это либо директория, либо новое название файла или директории.

Команда mv может:

  • Переместить один или несколько файлов в другую директорию.
  • Переместить одну или несколько директорий в другую директорию.
  • Переименовать файл.
  • Переименовать директорию.

Опции

  • none или off — не делать резервных копий, даже если включена опция —backup
  • numbered или t — имя резервной копии получит числовой индекс (пример: myfile.txt

).

  • existing или nil — если в директории уже есть резервные копии с числовыми индексами, то использовать числовые индексы для новых резервных копий, во всех остальных случаях использовать метод simple .
  • simple или never — делать обычные резервные копии (пример: myfile.txt

    Примеры использования команды mv

    Рассмотрим несколько примеров использования команды mv в Linux.

    Рекомендуется всегда использовать опцию -v , чтобы получать информацию о том, что именно команда mv делает с файлами.

    Также крайне рекомендуется использовать опцию -i , чтобы выдавался запрос на перезапись существующих файлов. В примерах ниже мы эти опции опускаем.

    Переместить файл

    Переместим файл myfile1.txt в директорию mydir/ (директория должна существовать). Для этого выполняем команду без каких-либо аргументов:

    Переименовать файл

    Переименуем файл myfile1.txt в myfile2.txt :

    Переименовать директорию

    Переименуем директорию mydir1 в mydir2 . Выполняется точно также, как и переименование файлов.

    Создавать резервные копии существующих файлов

    Предположим, что нам нужно переименовать файл myfile1.txt в myfile2.txt , но файл myfile2.txt уже существует. Можно воспользоваться опцией -b , чтобы создать резервную копию существующего файла:

    В результате сначала существующий файл myfile2.txt будет переименован в myfile2.txt

    , то есть будет создана его резервная копия, и только потом файл myfile1.txt будет переименован в myfile2.txt .

    Вместо значка тильда

    можно добавлять к именам резервных копий произвольный суффикс. Например, добавим суффикс .bak . Для этого воспользуемся опцией -S

    Переместить несколько файлов

    Рассмотрим примеры использования команды mv для перемещения нескольких файлов в другую директорию.

    Переместим сразу три файла в директорию mydir/

    Переместим все файлы из текущей директории в директорию mydir/

    Переместим все файлы с расширением .jpg в директорию mydir/

    Переместить только те файлы, которых нет в директории назначения

    Предположим, что нам нужно переместить все файлы из одной директории в другую, но если в директории назначения уже есть файлы с такими же именами, то их не перемещать. Для этого используем опцию -n

    Переместить только те файлы, которые новее

    Предположим, что нам нужно переместить все файлы из одной директории в другую, но если в другой директории уже есть файлы с такими же именами, то заменять существующие файлы только если исходный файл новее (по дате). Для этого используем опцию -u

    Если в имени файла есть пробелы

    Если в имени файла есть пробелы, то имя файла нужно заключить в кавычки или перед каждым пробелом добавлять символ

    Предположим, что нам нужно переименовать файл в имени которого содержится пробел — My file1.txt . Для этого можно заключить имя файла в кавычки (для файла назначения аналогично).

    Или использовать символ косой черты перед пробелом.

    How To Use Linux To Copy, Move Or Delete Files

    2019 December 2nd

    There are some big advantages to performing basic copy, move and delete functions through the Linux command line rather than a standard graphical user interface (GUI).

    For starters, it’s much faster and you can use it to automate file management operations with scripts or batch files.

    But the real plus of using the Linux command line is that operations that would be difficult in a GUI window become far easier.

    Today, I’m here to tell you how to copy, move and delete files from the Linux command line:

    1. How to Copy Files Using the cp Command

    cp is the Linux copy command. Using it is extremely straightforward, as it only requires two arguments.

    However, just because using cp to perform a basic copy function is simple, it doesn’t mean there isn’t plenty of room for customization. There are more than ten different modifiers which can be used by calling cp in the following manner.

    Here are some of the Linux copy file modifiers you can use:

    • cp -a : The archive modifier, it will preserve any copied files in their current state.
    • cp -f: The force option will ensure the copy is completed by overwriting identical files.
    • cp -i: This is the interactive option which will display an overwrite prompt for identical files.
    • cp -l: Creates a file that is hard linked to the source file, rather than a copy of it.
    • cp -L: This creates a soft link to the directory of the source file.
    • cp -n: This prevents overwriting of any identical files.
    • cp -p: Create a copy with the same modification and permissions as the original file.
    • cp -r: Perform a recursive copy that includes all folders and subdirectories of the source material.
    • cp -u: The update modification only copies the source file if it’s more recent than the destination file.
    • cp -v: The v stands for verbose. This option will display update messages during the copy.

    The recursive cp -r variant is the most important to remember. In a graphical interface, normally when a folder is copied, so are all subdirectories. Linux doesn’t do this by default. So, to copy directory Linux, make sure you add the -r !

    The archive -a command is also a versatile extension. It will produce a copy as close as possible to the original file that will include the same metadata and directory tree.

    1.1 Copy Single Files with cp

    If you want to Ubuntu copy file within your working directory, you can simply use the following line of code. In this case, I’ll use document.txt as my example file.

    This will create a copied version of your file named document-2.txt which will be stored alongside the original in the working directory. However, there’s no need for you to copy the file within the same directory.

    In this case, the copied file will be placed in the copied-documents folder. Note that I used the tilde shortcut here to refer to the home user directory. You can do this at any time in the Unix command terminal.

    1.2 Copy Multiple Files with cp

    There are two different ways cp can be used to copy multiple files to the same directory. The most basic method is to simply list multiple files in the source section of the command and then provide a destination directory instead of a destination file name.

    In the example above, the document and picture file will both be copied to the copied-documents folder from the home user root directory. If you are attempting to copy multiple files with similar names, you can use the wildcard asterisk modifier. For example, if you want to copy files named ‘ document-1.txt ‘ and ‘ document-2.txt ‘, you can do the following.

    The * tells Unix to copy any text files in the home directory that has a name beginning with ‘ document- ‘.

    2. How to Move Files Using the mv Command

    mv operates very similarly to cp , requiring only two arguments. Self-evidently, instead of just creating a copy of the source file, it will delete the original and replicate it in a different directory.

    Once again, it’s possible to change the way in which files are moved with an optional modifier.

    The modifiers listed for cp are also applicable for mv . Remember, the command terminal will automatically list these for you if you call a help command.

    However, there is one additional mv modification worth knowing about. This is the -b or ‘backup’ option, which will create a backup of the moved file in the source directory.

    2.1 Move Single Files with mv

    Once again, you will most commonly use the mv command to transfer files from one directory to another. In the following snippet, you’ll find a command to move an example text file.

    Note that there’s no need to keep the name of the file the same. While calling the mv command, you can rename the moved file anything you like.

    The line above will move the directory of the text file as well as renaming it. And here’s a tip, the Linux command line d oesn’t have a separate renaming function, so if you ever want to rename a file, just use the mv command ! For example, if I want to change the name of the document text file, but not its location, I can simply remove the folders from the above line of code.

    2.2 Move Multiple Files with mv

    Just like the cp command, there are two techniques you can use to move more than one file with mv . The first, and most basic, is to simply add multiple source files to the command line.

    This will move both the document text file and the picture file to the moved-documents folder. However, you can save yourself time by using the wild card operator.

    This code will move every text file from the user’s home folder into the text-files folder. Note that if that folder doesn’t exist already, this operation will create it.

    3. How to Delete Files Using the rm command

    The rm or ‘remove’ command is used to delete files from the Linux command line. If you paid attention to how to use the copy and move operators, you’ll be on familiar ground here. However, while those functions require two input arguments, you only need one to perform a deletion operation.

    Once again, you can use the same modification options I listed in section one with the rm function. If you ever forget what they are, just ask in the command line for help!

    3.1 Delete Single Files with rm

    Using the rm function to delete a file or directory is extremely simple. If, for example, we wanted to delete a file within a folder called text-files , contained in the home user folder, this line of code would suffice.

    rm can be used to delete directories too. If we wanted to remove the actual text-files folder itself, we could run the following operation.

    Note that when you call an rm operation on a directory, by default, only the subdirectories and files within the directory will be removed. That makes the recursive -r modifier one of the most useful rm options to know about.

    This line will not only delete the files contained in the text-files directory, but will remove the directory itself, too.

    3.2 Delete Multiple Files with rm

    To delete more than one file with rm , simply add extra files or folders as new arguments. The snippet below will delete both the document and picture files in the user home directory.

    You can also use the * wildcard operator to delete multiple files with the same name or file type. This example code will delete any text files within the text-files folder.

    But beware! Never ever combine the recursive delete operation with the wildcard operator alone. The following command will delete every file and directory you have permission to modify.

    How to Copy, Move and Delete Files in Linux — Conclusion

    Now you know how to copy, move and delete files from the Linux command line. If you internalize these commands, you’ll be able to perform file operations much faster and create batch commands or scripts.

    Remember, if you ever forget how to use a particular operation, you can refer back to this guide or use the man function to open the relevant part of the command line manual:

    Was this Linux copy file walkthrough useful? If you want to learn about other commands, let me know by commenting below!

    Written by Dani Nolan

    Dani Nolan Dani Nolan

    An experienced content professional with a creative mind. If I’m not writing, you can probably find me in the backyard playing with dogs or at some weird art show.

    Related posts

    5 Best Linux Hosting Providers – The Finest Yo.

    Linux is a powerful open-source operating system. When used for web hosting and servers, it can come in many shapes.

    Debian vs Ubuntu: The Complete Rundown of Linux Serv.

    Debian and Ubuntu are among the top Linux distributions available. Although Ubuntu is a way newer distro, both are equally.

    How to use mv command in Linux

    MV command is a command that similar to cp command, but it does not create a copy/duplicate of files/directories. When you want to move files from one place to another and you don’t want to duplicate it, we use mv command.

    This command is installed by default on your Linux system, in any kind of Linux you are using. Please take a look of some examples of using mv command in day-to-day operation.

    1) Moving files

    The requirement of moving file is the file source location must be different with the files destination location. Here’s an example. To move file_1.txt from current directory to another directory , for example /home/pungki/office, here’s the syntax :

    $ mv file_1.txt /home/pungki/office

    As we can see, when we move the file_1.txt, the file_1.txt from previous directory is deleted.

    2) Moving multiple files

    If we want to move multiple files, we put them in one line separated by space.

    $ mv file_2.txt file_3.txt file_4.txt /home/pungki/office

    You can also use a pattern if your files have it. For example, to move all files which have .txt extension, we can use this command :

    $ mv *.txt /home/pungki/office

    3) Moving directory

    Different from the copy command, moving directory using mv command is pretty straightforward. To move a directory, you can just to use mv command without any options. Please take a look screenshot below.

    4) Renaming files or directory

    We also use mv command to rename files and directory. But in order to do so, the destination location must be the same as the source location. Then the file name must be different.

    Let say we are inside /home/pungki/Documents folder and we want to rename file_1.txt into file_2.txt. Then the command will be like :

    $ mv file_1.txt file_2.txt

    If we mention the absolute path, then it will look like this :

    $ mv /home/pungki/Documents/file_1.txt /home/pungki/Documents/file_2.txt

    5) Renaming directory

    The above rule is also applied to a directory as well. Take a look at this example :

    $ mv directory_1/ directory_2/

    6) Print what happen

    When you are moving or renaming a large number of file/directory, you may want to know does your command works successfully or not without seeing to the destination location. To do this, we can use -v option.
    For example, we want to move all txt files and want to check it. Then the command will be like this.

    $ mv -v *.txt /home/pungki/office

    The same way is applied to the directory.

    7) Using interactive mode

    When you are moving file into another location, and there is already exist the same file, then by default mv will overwrite it. No pop-up notification for this. To make a notification for overwriting file, we can use -i option.

    Let say we want to move file_1.txt to /home/pungki/office. Meanwhile, file_1.txt is already existed in /home/pungki/office directory.

    $ mv -i file_1.txt /home/pungki/office

    This notification will aware us about the existence of file_1.txt in the destination location. If we press “y” then the file will be moved, otherwise, it will not.

    8) Using update option

    While -i are notifying us about overwriting files, then -u option will perform update only if the source is newer than destination file. Let’s take a look example below.

    We have file_1.txt and file_2.txt with this attributes :

    • File_1.txt has 84 bytes file size and it last modified time is 12:00
    • File_2.txt has 0 bytes file size and it last modified time is 11:59

    We want to move them into /home/pungki/office directory. But in the destination location, we already have file_1.txt and file_2.txt.

    We move file_1.txt and file_2.txt from current directory into /home/pungki/office using command :

    $ mv -uv *.txt /home/pungki/office

    As a result, we see those files are moved. That file is moved because their last modified timestamp is newer than the files in /home/pungki/office directory.

    9) Do not overwrite any existing file

    If -i options is asking us about overwriting files, than -n option will not allow us to overwrite any existing files.

    Using example on point 8, if we change the option from -u to -n, combine with -v option, then we will see that there are no files moved into /home/pungki/office directory.

    $ mv -vn *.txt /home/pungki/office

    10) Create backup when copying

    By default, moving files will overwrite the destination files if there are already exist before. But what happens if you are moving wrong files, and the destination files are already overwritten by the new ones? Is there a way to retrieve the old one? Yes there is. We can use -b option. -b option will make a backup of destination file before it overwritten by the new one. Once again, we will use the scenario from point 8 above.

    $ mv -bv *.txt /home/pungki/office

    As you can see on the screenshot, on the /home/pungki/office directory, we have a file named file_1.txt

    and file_2.txt

    . The tilde sign (

    ) means that those files are backup. We can see the attribute of them is older than file_1.txt and file_2.txt.

    Moving file or directory also one of the basic commands in the Linux system. As usual, you can type man mv or mv —help to display its manual page to explore more detail.

    How to Move, Copy, and Delete Files in Linux

    Aha! Simple, you say. Just go to the graphical interface you’re using for your Linux system. Then you can quickly and easily move the file of your choice from one place to another, copy it, or zap it into nothingness.

    Now, what if you wanted to move (or copy or delete) many files at the same time? In particular, what if you wanted to move all files with the same characters at the end of their name, like joe_expenses, cath_expenses, mike_expenses and robin_expenses?

    3 Commands to Use in the Linux Command Line:

    In the case mentioned above, the Linux command line offers far greater power and efficiency than the GUI. For instance, to instantly seek out and move all of the files above to a subdirectory called budget, your command line instruction would simply be:

    Each of the Linux commands to move, copy, or delete files have options to make it more productive. Read on to find out more.

    1. mv: Moving (and Renaming) Files

    The mv command lets you move a file from one directory location to another. It also lets you rename a file (there is no separate rename command).

    Let’s start with the basic format:

    In this case, if JOE1_expenses does not exist, it will be created with the exact content of joe_expenses, and joe_expenses will disappear.

    If JOE1_expenses already exists, its content will be replaced with that of joe_expenses (and joe_expenses will still disappear).

    Additional Options

    Options for mv include:

    -i for interactive, asks you to confirm if an existing file should be over written.

    -f for force, overrides all interactivity and executes the mv instruction without returning any prompts. (You must be sure your instruction is exactly what you want if you decide to apply the -f option.)

    -v for verbose, to show the files being moved one by one

    2. cp: Copying Files

    A basic example of the cp command to copy files (keep the original file and make a duplicate of it) might look like:

    In this example, we copy the joe_expenses file to the cashflow directory, which (because we haven’t specified anything else) is in our login directory.

    Additional Options

    Options are similar to those for the mv command:

    -i for interactive, asks you to confirm if an existing file (perhaps a version of joe_expenses already exists in the cashflow directory) should be over written in the copying process.

    -r for recursive, to copy all the subdirectories and files in a given directory and preserve the tree structure.

    -v for verbose, shows files being copied one by one. For example:

    3. rm: Deleting Files

    File deletion is done using the rm (remove) command.

    This will delete the joe_expenses file forever (maybe Joe would like that!).

    Additional Options

    Like the commands above, it can also be applied to more than one file at a time.

    This will remove both of these files.

    Using the wildcard character: “*”

    This will remove joe_expenses , cath_expenses , mike_expenses, and robin_expenses , forever.

    Likewise, if you decide you want to remove everything you copied into the cashflow directory above and the directory itself, use:

    Linux System Health Warning: Use Caution with These Commands

    For each of these commands, the use of the -i (interactive) option is highly recommended, at least in the beginning. This gives you a second chance to spot any unfortunate mistakes.

    Similarly, use caution if you apply either -f (force) or -r (recursive), especially if you are also using a wildcard character like “*” to apply the command to several files at once.

    Beware of the -r Option!

    We’ll say it once and once only. Don’t do this:

    This will delete every file and every directory you have.

    Happy Moving! (Or Copying Or Deleting!)

    May the force of mv, cp, and rm in the Linux command line be with you, but also make sure you avoid any disasters!

    Читать еще:  Оптимизация диска что это
  • Ссылка на основную публикацию
    Adblock
    detector