Linux move file with replace

mv moves a file, and ln -s creates a symbolic link, so the basic task is accomplished by a script that executes these two commands:

There are a few caveats. If the second argument is a directory, then mv would move the file into that directory, but ln -s would create a link to the directory rather than to the moved file.

#!/bin/sh set -e original="$1" target="$2" if [ -d "$target" ]; then target="$target/$" fi mv -- "$original" "$target" ln -s -- "$target" "$original" 

Another caveat is that the first argument to ln -s is the exact text of the symbolic link. It’s relative to the location of the target, not to the directory where the command is executed. If the original location is not in the current directory and the target is not expressed by an absolute path, the link will be incorrect. In this case, the path needs to be rewritten. In this case, I’ll create an absolute link (a relative link would be preferable, but it’s harder to get right). This script assumes that you don’t have file names that end in a newline character.

#!/bin/sh set -e original="$1" target="$2" if [ -d "$target" ]; then target="$target/$" fi mv -- "$original" "$target" case "$original" in */*) case "$target" in /*) :;; *) target="$(cd -- "$(dirname -- "$target")" && pwd)/$" esac esac ln -s -- "$target" "$original" 

If you have multiple files, process them in a loop.

#!/bin/sh while [ $# -gt 1 ]; do eval "target=\$" original="$1" if [ -d "$target" ]; then target="$target/$" fi mv -- "$original" "$target" case "$original" in */*) case "$target" in /*) :;; *) target="$(cd -- "$(dirname -- "$target")" && pwd)/$" esac esac ln -s -- "$target" "$original" shift done 

Источник

mv Command in Linux: 7 Essential Examples

mv command in Linux is used for moving and renaming files and directories. In this tutorial, you’ll learn some of the essential usages of the mv command.

mv is one of the must known commands in Linux. mv stands for move and is essentially used for moving files or directories from one location to another.

The syntax is similar to the cp command in Linux however there is one fundamental difference between these two commands.

You can think of the cp command as a copy-paste operation. Whereas the mv command can be equated with the cut-paste operation.

Читайте также:  Testdisk linux filesys data

Which means that when you use the mv command on a file or directory, the file or directory is moved to a new place and the source file/directory doesn’t exist anymore. That’s what a cut-paste operation, isn’t it?

mv command can also be used for renaming a file. Using mv command is fairly simple and if you learn a few options, it will become even better.

7 practical examples of the mv command

Let’s see some of the useful examples of the mv command.

1. How to move a file to different directory

The first and the simplest example is to move a file. To do that, you just have to specify the source file and the destination directory or file.

mv source_file target_directory

This command will move the source_file and put it in the target_directory.

2. How to move multiple files

If you want to move multiple files at once, just provide all the files to the move command followed by the destination directory.

mv file1.txt file.2.txt file3.txt target_directory

You can also use glob to move multiple files matching a pattern.

For example in the above example, instead of providing all the files individually, you can also use the glob that matches all the files with the extension .txt and moves them to the target directory.

3. How to rename a file

One essential use of mv command is in renaming of files. If you use mv command and specify a file name in the destination, the source file will be renamed to the target_file.

mv source_file target_directory/target_file

In the above example, if the target_fille doesn’t exist in the target_directory, it will create the target_file.

However, if the target_file already exists, it will overwrite it without asking. Which means the content of the existing target file will be changed with the content of the source file.

I’ll show you how to deal with overwriting of files with mv command later in this tutorial.

You are not obliged to provide a target directory. If you don’t specify the target directory, the file will be renamed and kept in the same directory.

Keep in mind: By default, mv command overwrites if the target file already exists. This behavior can be changed with -n or -i option, explained later.

4. How to move a directory in Linux with mv command

You can use mv command to move directories as well. The command is the same as what we saw in moving files.

mv source_directory target_directory

In the above example, if the target_directory exists, the entire source_directory will be moved inside the target_directory. Which means that the source_directory will become a sub-directory of the target_directory.

5. How to rename a directory

Renaming a directory is the same as moving a directory. The only difference is that the target directory must not already exist. Otherwise, the entire directory will be moved inside it as we saw in the previous directory.

mv source_directory path_to_non_existing_directory

6. How to deal with overwriting a file while moving

If you are moving a file and there is already a file with the same name, the contents of the existing file will be overwritten immediately.

Читайте также:  Настройка bind alt linux

This may not be ideal in all the situations. You have a few options to deal with the overwrite scenario.

To prevent overwriting existing files, you can use the -n option. This way, mv won’t overwrite existing files.

mv -n source_file target_directory

But maybe you want to overwrite some files. You can use the interactive option -i and it will ask you if you want to overwrite existing file(s).

mv -i source_file target_directory mv: overwrite 'target_directory/source_file'?

You can enter y for overwriting the existing file or n for not overwriting it.

There is also an option for making automatic backups. If you use -b option with the mv command, it will overwrite the existing files but before that, it will create a backup of the overwritten files.

mv -b file.txt target_dir/file.txt ls target_dir file.txt file.txt~

By default, the backup of the file ends with ~. You can change it by using the -S option and specifying the suffix:

mv -S .back -b file.txt target_dir/file.txt ls target_dir file.txt file.txt.back

You can also use the update option -u when dealing with overwriting. With the -u option, source files will only be moved to the new location if the source file is newer than the existing file or if it doesn’t exist in the target directory.

  • -i : Confirm before overwriting
  • -n : No overwriting
  • -b : Overwriting with backup
  • -u : Overwrite if the target file is old or doesn’t exist

7. How to forcefully move the files

If the target file is write protected, you’ll be asked to confirm before overwriting the target file.

mv file1.txt target mv: replace 'target/file1.txt', overriding mode 0444 (r--r--r--)? y

To avoid this prompt and overwrite the file straightaway, you can use the force option -f.

If you do not know what’s write protection, please read about file permissions in Linux.

You can further learn about mv command by browsing its man page. However, you are more likely to use only these mv commands examples I showed here. FYI, you may also use rename command for renaming multiple files at once.

I hope you like this article. If you have questions or suggestions, please feel free to ask in the comment section below.

Источник

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

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

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

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

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

mv [OPTIONS] SOURCE DESTINATION 

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

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

Чтобы переместить файл или каталог, вам необходимо иметь права на запись как в 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 спросит вас, хотите ли вы перезаписать файл:

mv: replace '/tmp/file1', overriding mode 0400 (r--------)? 

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

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

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

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

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

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

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

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

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

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

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

Выводы

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

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

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

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

Источник

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