Linux move many files

Как перемещать файлы и каталоги в Linux (команда mv)

Перемещение файлов и каталогов — одна из самых основных задач, которые вам часто приходится выполнять в системе Linux.

В этом руководстве мы объясним, как использовать команду mv для перемещения файлов и каталогов.

Как использовать команду mv

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

SOURCE может быть одним или несколькими файлами или каталогами, а DESTINATION может быть одним файлом или каталогом.

  • Когда в качестве SOURCE задано несколько файлов или каталогов, DESTINATION должен быть каталогом. В этом случае файлы SOURCE перемещаются в целевой каталог.
  • Если вы укажете один файл как SOURCE , а целью DESTINATION является существующий каталог, то файл будет перемещен в указанный каталог.
  • Если вы укажете один файл в качестве SOURCE и один файл в качестве цели DESTINATION вы переименуете файл .
  • Если SOURCE является каталогом, а DESTINATION не существует, SOURCE будет переименован в DESTINATION . В противном случае, если DESTINATION существует, он будет перемещен в каталог DESTINATION .

Чтобы переместить файл или каталог, вам необходимо иметь права на запись как в SOURCE и в DESTINATION . В противном случае вы получите сообщение об ошибке в разрешении отказано.

Например, чтобы переместить файл file1 из текущего рабочего каталога в каталог /tmp вы должны запустить:

Чтобы переименовать файл, вам необходимо указать имя файла назначения:

Синтаксис перемещения каталогов такой же, как и при перемещении файлов. В следующем примере, если каталог dir2 существует, команда переместит dir1 внутрь dir2 . Если dir2 не существует, dir1 будет переименован в dir2 :

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

Чтобы переместить несколько файлов и каталогов, укажите файлы, которые вы хотите переместить, в качестве источника. Например, чтобы переместить файлы file1 и file2 в каталог dir1 , введите:

Команда mv также позволяет использовать сопоставление с образцом. Например, чтобы переместить все файлы pdf из текущего каталога в каталог

/Documents , вы должны использовать:

Параметры команды mv

Команда mv принимает несколько параметров, которые влияют на поведение команды по умолчанию.

В некоторых дистрибутивах Linux mv может быть псевдонимом команды mv с настраиваемым набором параметров. Например, в CentOS mv — это псевдоним mv -i . Вы можете узнать, является ли mv псевдонимом, используя команду type :

Если mv является псевдонимом, вывод будет выглядеть примерно так:

Если указаны конфликтующие варианты, последний имеет приоритет.

Запрашивать перед перезаписью

По умолчанию, если целевой файл существует, он будет перезаписан. Чтобы запросить подтверждение, используйте параметр -i :

Чтобы перезаписать файл типа y или Y

Принудительная перезапись

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

Чтобы не получать подсказки, используйте параметры -f :

Эта опция особенно полезна, когда вам нужно перезаписать несколько файлов, доступных только для чтения.

Не перезаписывать существующие файлы

Параметр -n указывает mv никогда не перезаписывать существующие файлы:

Если существует file1 приведенная выше команда ничего не сделает. В противном случае он переместит файл в каталог /tmp .

Резервное копирование файлов

Если целевой файл существует, вы можете создать его резервную копию, используя параметр -b :

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

Используйте команду ls, чтобы убедиться, что резервная копия была создана:

Подробный вывод

Другой вариант, который может быть полезен, — это -v . Когда используется эта опция, команда печатает имя каждого перемещенного файла:

Выводы

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

Для получения дополнительных сведений о команде mv страницу руководства или введите в терминале man mv .

Читайте также:  Dns сервер не отвечает windows 10 как исправить wifi ростелеком

Новые пользователи Linux, которых пугает командная строка, могут использовать файловый менеджер с графическим интерфейсом для перемещения своих файлов.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

How to Move Files Using Linux Commands or File Managers

Learn how to move files with Linux commands in this tutorial from our archives.

There are certain tasks that are done so often, users take for granted just how simple they are. But then, you migrate to a new platform and those same simple tasks begin to require a small portion of your brain’s power to complete. One such task is moving files from one location to another. Sure, it’s most often considered one of the more rudimentary actions to be done on a computer. When you move to the Linux platform, however, you may find yourself asking “Now, how do I move files?”

If you’re familiar with Linux, you know there are always many routes to the same success. Moving files is no exception. You can opt for the power of the command line or the simplicity of the GUI – either way, you will get those files moved.

Let’s examine just how you can move those files about. First we’ll examine the command line.

Command line moving

One of the issues so many users, new to Linux, face is the idea of having to use the command line. It can be somewhat daunting at first. Although modern Linux interfaces can help to ensure you rarely have to use this “old school” tool, there is a great deal of power you would be missing if you ignored it all together. The command for moving files is a perfect illustration of this.

The command to move files is mv . It’s very simple and one of the first commands you will learn on the platform. Instead of just listing out the syntax and the usual switches for the command – and then allowing you to do the rest – let’s walk through how you can make use of this tool.

The mv command does one thing – it moves a file from one location to another. This can be somewhat misleading, because mv is also used to rename files. How? Simple. Here’s an example. Say you have the file testfile in /home/jack/ and you want to rename it to testfile2 (while keeping it in the same location). To do this, you would use the mv command like so:

mv /home/jack/testfile /home/jack/testfile2

or, if you’re already within /home/jack:

mv testfile testfile2

The above commands would move /home/jack/testfile to /home/jack/testfile2 – effectively renaming the file. But what if you simply wanted to move the file? Say you want to keep your home directory (in this case /home/jack) free from stray files. You could move that testfile into /home/jack/Documents with the command:

mv /home/jack/testfile /home/jack/Documents/

With the above command, you have relocated the file into a new location, while retaining the original file name.

What if you have a number of files you want to move? Luckily, you don’t have to issue the mv command for every file. You can use wildcards to help you out. Here’s an example:

You have a number of .mp3 files in your

/ – is an easy way to represent your home directory – in our earlier example, that would be /home/jack/) and you want them in

/Music. You could quickly move them with a single command, like so:

That command would move every file that ended in .mp3 from the Downloads directory, and move them into the Music directory.

Should you want to move a file into the parent directory of the current working directory, there’s an easy way to do that. Say you have the file testfile located in

/Downloads and you want it in your home directory. If you are currently in the

/Downloads directory, you can move it up one folder (to

The “../” means to move the folder up one level. If you’re buried deeper, say

Читайте также:  Почему после запуска windows

/Downloads/today/, you can still easily move that file with:

Just remember, each “../” represents one level up.

As you can see, moving files from the command line, isn’t difficult at all.

There are a lot of GUIs available for the Linux platform. On top of that, there are a lot of file managers you can use. The most popular file managers are Nautilus (GNOME) and Dolphin (KDE). Both are very powerful and flexible. I want to illustrate how files are moved using the Nautilus file manager (on the Ubuntu 13.10 distribution, with Unity as the interface).

Nautilus has probably the most efficient means of moving files about. Here’s how it’s done:

Open up the Nautilus file manager.

Locate the file you want to move and right-click said file.

From the pop-up menu (Figure 1) select the “Move To” option.

When the Select Destination window opens, navigate to the new location for the file.

Once you’ve located the destination folder, click Select.

This context menu also allows you to copy the file to a new location, move the file to the Trash, and more.

If you’re more of a drag and drop kind of person, fear not – Nautilus is ready to serve. Let’s say you have a file in your home directory and you want to drag it to Documents. By default, Nautilus will have a few bookmarks in the left pane of the window. You can drag the file into the Document bookmark without having to open a second Nautilus window. Simply click, hold, and drag the file from the main viewing pane to the Documents bookmark.

If, however, the destination for that file is not listed in your bookmarks (or doesn’t appear in the current main viewing pane), you’ll need to open up a second Nautilus window. Side by side, you can then drag the file from the source folder in the original window to the the destination folder in the second window.

If you need to move multiple files, you’re still in luck. Similar to nearly every modern user interface, you can do multi-select of files by holding down the Ctrl button as you click each file. After you have selected each file (Figure 2), you can either right-click one of the selected files and the choose the Move To option, or just drag and drop them into a new location.

The selected files (in this case, folders) will each be highlighted.

Moving files on the Linux desktop is incredibly easy. Either with the command line or your desktop of choice, you have numerous routes to success – all of which are user-friendly and quick to master.

Источник

How to move a file in Linux | Opensource.com

Whether you’re new to moving files in Linux or experienced, you’ll learn something in this in-depth writeup.

Subscribe now

Get the highlights in your inbox every week.

Moving files in Linux can seem relatively straightforward, but there are more options available than most realize. This article teaches beginners how to move files in the GUI and on the command line, but also explains what’s actually happening under the hood, and addresses command line options that many experience users have rarely explored.

Moving what?

Before delving into moving files, it’s worth taking a closer look at what actually happens when moving file system objects. When a file is created, it is assigned to an inode, which is a fixed point in a file system that’s used for data storage. You can what inode maps to a file with the ls command:

When you move a file, you don’t actually move the data from one inode to another, you only assign the file object a new name or file path. In fact, a file retains its permissions when it’s moved, because moving a file doesn’t change or re-create it.

File and directory inodes never imply inheritance and are dictated by the filesystem itself. Inode assignment is sequential based on when the file was created and is entirely independent of how you organize your computer. A file «inside» a directory may have a lower inode number than its parent directory, or a higher one. For example:

Читайте также:  Можно ли изменить цвет панели задач windows 10

When moving a file from one hard drive to another, however, the inode is very likely to change. This happens because the new data has to be written onto a new filesystem. For this reason, in Linux the act of moving and renaming files is literally the same action. Whether you move a file to another directory or to the same directory with a new name, both actions are performed by the same underlying program.

This article focuses on moving files from one directory to another.

Moving with a mouse

The GUI is a friendly and, to most people, familiar layer of abstraction on top of a complex collection of binary data. It’s also the first and most intuitive way to move files on Linux. If you’re used to the desktop experience, in a generic sense, then you probably already know how to move files around your hard drive. In the GNOME desktop, for instance, the default action when dragging and dropping a file from one window to another is to move the file rather than to copy it, so it’s probably one of the most intuitive actions on the desktop:

gnome-mv.jpg

The Dolphin file manager in the KDE Plasma desktop defaults to prompting the user for an action. Holding the Shift key while dragging a file forces a move action:

Источник

How to move multiple files at once to a specific destination directory?

I got a bunch of files in some directory (along with many other files) that I want to move.

Luckily, all the files I want to move contain a certain identifier in their names, so I can ls | grep IDENTIFIER to get the exact list of files to move.

But, how can I execute mv file /path/to/dest/folder/ at once, and not one by one (there’s a lot of files to move)?

14 Answers 14

The following also works, but I’m not sure if mv is invoked multiple times or not, as grep will output a new line for each match:

If you want to move ABC-IDENTIFIER-XYZ.ext or IDENTIFIER-XYZ.xml , you can use:

* is a wildcard for zero or more characters, this means zero or more characters, followed by IDENTIFIER , followed by zero or more characters.

This will move all the files that contain the IDENTIFIER you specified.

Fore example, to move all files having a .doc extension:

This will move all doc file under the current directory to the specific destination.

Edit

To answer the comment:

but the list of files to move is not determined by extension. some of the files are named: ABC-IDENTIFIER-XYZ.ext and some just IDENTIFIER-XYZ.ext all having different extensions, mostly xml or properties .

If you want to move a set of arbitrary files (no common pattern in the names and types) you can do as Mr. Rajanand said: first go to the directory that contains the files you want to move

In case the files are scattered in different directories, you only need to specify the path for each file in the mv command.

I use tuomaz’s technique, but slightly modified:

I find this easier to remember and harder to screw up since it uses the same ordering as the vanilla mv operation:

If the files are in the same dir you can use

(tested in Ubuntu 16.04)

Use this command:

However, ls is not recommended for this kind of use. Use find command instead.

If you have so many files to move you can actually have too many for the mv command (or other commands like rm ). I suggest using xargs to move each file individually in a loop like fashion. One way to get around that is to do:

The ls -1 (minus one) ensures that there is only one filename on each line. If you have hidden aliases for the ls command you can have multiple filenames on a single line and inadvertently move a file you did not intend to move.

Источник

Оцените статью