Naming file in linux

Как переименовать файлы и каталоги в Linux

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

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

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

Переименование файлов с помощью команды mv

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

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

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

Например, чтобы переименовать файл file1.txt в file2.txt вы должны запустить:

Переименование нескольких файлов с помощью команды mv

Команда mv может переименовывать только один файл за раз, но ее можно использовать вместе с другими командами, такими как find или inside bash for циклов for или while для переименования нескольких файлов.

В следующем примере показано, как использовать цикл for в Bash для переименования всех файлов .html в текущем каталоге, изменив расширение .html на .php .

Давайте проанализируем код построчно:

  • Первая строка создает цикл for и выполняет итерацию по списку всех файлов с .html .
  • Вторая строка применяется к каждому элементу списка и перемещает файл в новый, заменяя .html на .php . Часть $ использует расширение параметра оболочки для удаления части .html из имени файла.
  • done указывает конец сегмента цикла.

Вот пример использования mv в сочетании с find для достижения того же, что и выше:

Команда find передает все файлы, заканчивающиеся на .html в текущем каталоге, в mv один за другим с использованием параметра -exec . Строка <> — это имя файла, который в данный момент обрабатывается.

Как видно из приведенных выше примеров, переименование нескольких файлов с помощью команды mv — непростая задача, поскольку для этого требуется хорошее знание сценариев Bash.

Переименование файлов с помощью команды rename

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

Есть две версии команды rename с разным синтаксисом. В этом руководстве мы будем использовать Perl-версию команды rename . Если в вашей системе не установлена эта версия, вы можете легко установить ее с помощью диспетчера пакетов вашего дистрибутива.

Установить rename в Ubuntu и Debian

Установить rename в CentOS и Fedora

Установить rename в Arch Linux

Синтаксис команды rename следующий:

Команда rename переименует files соответствии с указанным регулярным выражением perlexpr . Вы можете узнать больше о регулярных выражениях Perl здесь .

В следующем примере все файлы с расширением .html изменятся на .php :

Вы можете использовать параметр -n для вывода имен файлов, которые нужно переименовать, без их переименования.

Результат будет выглядеть примерно так:

По умолчанию команда rename не перезаписывает существующие файлы. Передайте параметр -f чтобы разрешить перезапись существующих файлов:

Ниже приведены еще несколько распространенных примеров использования команды rename :

Замените пробелы в именах файлов символами подчеркивания

Преобразование имен файлов в нижний регистр

Преобразование имен файлов в верхний регистр

Выводы

Мы показали вам, как использовать команды mv и rename для переименования файлов.

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

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

Источник

Linux / UNIX: Rules For Naming File And Directory Names

C an you specify rules for naming file and directory names under Linux and UNIX operating systems?

Following are general rules for both Linux, and Unix (including *BSD) like systems:

  1. All file names are case sensitive. So filename vivek.txt Vivek.txt VIVEK.txt all are three different files.
  2. You can use upper and lowercase letters, numbers, “.” (dot), and “_” (underscore) symbols.

Linux / UNIX: Reserved Characters And Words

Avoid using the following characters from appearing in file names:

Please note that Linux and UNIX allows white spaces, , |, \, :, (, ), &, ;, as well as wildcards such as ? and *, to be quoted or escaped using \ symbol.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

See also:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

File Naming Conventions in Linux

A file name, also called a filename, is a string (i.e., a sequence of characters) that is used to identify a file.

A file is a collection of related information that appears to the user as a single, contiguous block of data and that is retained in storage, e.g., a hard disk drive (HDD), floppy disk, optical disk or magnetic tape. Names are given to files on Unix-like operating systems to enable users to easily identify them and to facilitate finding them again in the future.

However, file names are only a convenience for users, and such operating systems identify files by their inodes, which are numbers that are stored on the HDD in inode tables and which exist for all types of files, rather than by their names or locations in directories.

This is somewhat analogous to the domain names that are used on the Internet to identify web sites. The names are only for the convenience of human users of the system, and each site is identified by the network by a set of numbers referred to as an IP address.

File names in Linux can contain any characters other than (1) a forward slash ( / ), which is reserved for use as the name of the root directory (i.e., the directory that contains all other directories and files) and as a directory separator, and (2) the null character (which is used to terminate segments of text). Spaces are permitted, although they are best avoided because they can be incompatible with legacy software in some cases.

Typically, however, file names only use alphanumeric characters (mostly lower case), underscores, hyphens and periods. Other characters, such as dollar signs, percentage signs and brackets, have special meanings to the shell and can be distracting to work with. File names should never begin with a hyphen.

A relatively small number of file names on a system consist only of upper case characters, such as README, INSTALL, NEWS and AUTHORS. They are usually plain text files that come bundled with programs and are for documentation purposes.

File names were limited to 14 bytes (equivalent to 14 characters) in early UNIX systems. However, modern Unix-like systems support long file names, usually up to 255 bytes in length. File names can be as short as a single character.

In some operating systems, such as MS-DOS and the Microsoft Windows systems, file names consist of two parts: a user-designated name and an extension which is determined by the type of file. The two are separated by a period.

Although Unix-like operating systems generally do not require the use of file extensions, they can be convenient and useful. In particular, they can make it easy to identify file types at a glance and to facilitate manipulating groups of files. Files can also have multiple extensions, such as ghex-2.6.0.tar.gz.

File names must be unique within a directory. However, multiple files and directories with the same name can reside in different directories because such files will have different absolute pathnames (i.e., locations relative to the root directory), and thus the system will be able to distinguish them.

In Unix-like operating systems, directories are just a special type of file, and thus their naming conventions are similar to those for ordinary files. The major exception is the root directory, whose name is always a forward slash.

In documentation, it is usually sufficient to refer to files and directories by their names rather than by their absolute pathnames. However, the first tier of directories in the root directory are usually referred to by their absolute pathnames, e.g., /bin, /boot, /etc, /home and /usr.

There are several ways to change the name of a file or directory. One is to use the mv (i.e., move) command. Thus, for example, to change the name of a file named file1 to file2, the following would be used:

When working in a GUI (graphical user interface), a name can be changed by using the right mouse button to click on an icon (i.e., small image) representing a file or a directory and selecting the Rename item in the menu that appears. The cursor is moved to the label for that item and the new name can then be typed in.

On a Unix-like operating system any file or directory can have multiple names because of the operating system’s use of inodes instead of names to identify files and directories. Additional names can be provided by using the ln command to create one or more hard links to a file or directory.

Created July 21, 2005.
Copyright © 2005 The Linux Information Project. All Rights Reserved.

Источник

Best practice for naming files in Linux

1 Minute, 17 Seconds to Read

If you are developing your website and you cannot find out why your pages, images, JavaScripts, and other web data is causing a 404 error not found, you may have a problem with case sensitivity.

Linux servers are case sensitive. Windows servers are not case sensitive, so if you are moving your files from a Windows development platform to a Linux web platform you may need to watch out for the following common mistakes.

Common Case Sensitive errors

Mixing Upper case and lower case

A common mistake is naming files a mixture of upper case and lower case. Like the following:

Linux reads the file name exactly the way its typed. So,

Is NOT the same as:

Incorrectly types file extension

File extensions are case sensitive as well. Some file types have 4 letters and others 3. See the following example:

Likewise, file extensions need to be exact as well:

Is NOT the same as:

Also, image extensions must be the right type:

Is NOT the same as:

Best practice for Linux file naming

To prevent running into problems with your file paths on your site, we recommend following the best practices for file naming. See the below:

  1. Name all your files lower case.
  2. Instead of using a space, use an ( _ ) or a ( – )
  3. Use consistent file types. Use jpg or jpg. Don’t use both.
  4. Only alphanumeric characters, periods, underscores and hyphens and don’t use symbols like “%”, “$”, and so forth.
  5. Keep the file names short and descriptive.

Comments

It looks like this article doesn’t have any comments yet — you can be the first. If you have any comments or questions, start the conversation!

Источник

How to Easily Rename Files in Linux

Renaming files is not a particularly advanced operation; as long as it’s done on a small number of files, it usually doesn’t require special tools. However, when there’s an entire folder of photos from last year’s vacation waiting to be renamed, it may be wise to consider some timesaving tricks or apps.

There are two general approaches when you rename files in Linux: via the command-line interface or a standalone application. Linux users already know how powerful the CLI can be, so it shouldn’t be surprising that there are several commands for file renaming.

Also read: How to Copy and Paste Text, Files and Folders in Linux Terminal

Renaming Files with “mv” Command

A simple way to rename files in Linux is with the mv command (shortened from “move”). Its primary purpose is moving files and folders, but it can also rename them, since the act of renaming a file is interpreted by the filesystem as moving it from one name to another.

The following syntax is used to rename files with mv:

“filename1.ext” is the original name of the file, and “filename2.ext” is the new name.

The same pattern works for renaming folders. If the files are not located in the currently active folder, their full path has to be specified:

Note that the mv command requires write permission for the folder containing the files. In the case of system files and folders, the user needs to obtain root permissions to rename files by prepending mv with sudo . An extra layer of protection is provided by the -i (interactive) option, which asks the user to confirm the file rename before it’s actually applied.

There’s also the -v (verbose) option, which lists all changes that have been made by mv . Options are written after mv but before the filenames.

Using the “rename” Command

This command to rename files in Linux is slightly more advanced than mv because it requires the knowledge of, or at least a basic familiarity with, regular expressions. That may sound scary, but don’t give up on rename just yet – it can be used for plain batch renaming simply by following tutorials like this one.

In many distributions of Linux, the rename command may not be available by default. If you are unable to use it in yours, you will have to install it.

In Debian-based Linux, type this in your terminal:

In Arch-based Linux:

The rename syntax looks like this:

The letter “s” stands for “substitute,” and it’s the main part of the regular expression. Single quotes around it are obligatory. Available options are:

  • -v (verbose: prints the list of renamed files along with their new names)
  • -n (“no action:” a test mode or simulation which only shows the files that will be changed without touching them)
  • -f (a forced overwrite of the original files)

The rename command also accepts wildcards to rename multiple files of the same type, and it works on file extensions as well. For example, this would change all files with the extension .jpeg to .jpg:

The wildcard symbol (*) means that all files in the folder will be affected.

The regular expression also has its own options (modifiers): “g” (global: affects all occurrences of the expression) and “i” (performs case-insensitive substitution). They are written at the end of the expression just before the closing single quote and can be combined:

This would apply to all .jpg files that contain “DSC,” “dSC,” and “dsc” – change that part of the filename to “photo.” However, because of the “-n” option, the command wouldn’t actually rename the files but just print them in the console window.

Substitution is not the only thing this regular expression can do. There’s also translation – marked by the letter “y” – which can transform the filenames on a more complex level. It is most often used to change the filename case:

This would change the names of all .jpg files from lowercase to uppercase. To do it in the reverse, just switch the “oldname” and “newname” parts of the regular expression.

Using the rename command boils down to mixing a few basic patterns to achieve the desired result. Thanks to the -n option, the users will never have to put their files at risk (or their nerves at stake) since it offers a safe and useful preview of what the renamed files will look like.

Also read: How to Fix the “No Space Left on Device” Error on Linux

Métamorphose2

Métamorphose is a cross-platform file and folder mass renamer. For those who prefer a GUI tool for carrying out renaming operations, Métamorphose is quite a powerful tool to use. It is available for both Windows and Linux.

To get started, go to its website and download the installer file for your distro. It provides a deb file for Debian-based distro and RPM package for Fedora, Mandriva and SUSE.

Once you run the app, it will be the first “Picker” tab. This is where you select the directory that contains the files you want to batch rename. Do note that it only supports one directory per renaming operation, though it can recurse through child folders within the selected directory.

After selecting the directory, click on the “Renamer” tab. From here you can decide on the renaming rules. On the left pane you can select the action you want to perform. For example, “insert” will insert terms to the name, while “length” allows you to trim the file name to a number of characters. There are also the “move text,” “replace” and “modify” options you can choose. As you can see, it provides extensive options for you to rename your files.

Lastly, just click the “Go” button at the top of the bottom pane to run the renaming action. If you find any error after renaming, there is an Undo option to revert all the changes.

Also read: How to Use the lp Command in Linux to Print Files From Terminal

pyRenamer – The Easy Way Out

Finally, the solution that all the anti-console users have been waiting for: a desktop application where everything can be done with a simple click of the mouse. pyRenamer is a crazy-powerful file renaming tool written in Python, which can be found here. Users of Ubuntu and its derivatives can install pyRenamer from the repositories using the command:

The interface consists of four parts:

  1. Tree-view file browser for selecting files and folders
  2. Central preview pane showing the filenames before and after renaming
  3. Tabbed control area for choosing the renaming criteria
  4. Options sidebar

pyRenamer can remove accents and duplicate symbols from filenames; replace any string of text with another; 20names to uppercase, lowercase or sentence case; and automatically insert or remove spaces and underscores. Beginners will love it because all of this can simply be selected in the tabbed area, previewed in the main area and confirmed by clicking Rename. If they wish to experiment with patterns, pyRenamer provides a cheatsheet to make it easier.

Advanced users will appreciate pyRenamer’s ability to rename multimedia files by reading from their metadata. It’s also possible to manually rename a single file when a batch rename is unnecessary.

In essence, pyRenamer wraps the functionality of the mv and remove commands into a user-friendly GUI. It’s a great choice for those who aren’t confident in their CLI skills.

Now that you know how to rename files in Linux, you may want to learn how to recursively change file permissions. Read on to learn how to diagnose a slow-running Linux computer or perhaps make use of the Hosts file to block/access websites.

Miguel has been a business growth and technology expert for more than a decade and has written software for even longer. From his little castle in Romania, he presents cold and analytical perspectives to things that affect the tech world.

Источник

Читайте также:  Топ архиваторов для linux
Оцените статью