- File Naming Conventions in Linux
- How to Read a Filename with Spaces in Linux
- 1) Creating file names with spaces
- 2) Read a File with spaces in filename
- 3) Creating directory names with spaces
- 4) Navigating to a directory with spaces in the directory name
- 5) Copying a directory with spaces in the directory name
- Linux / UNIX: Rules For Naming File And Directory Names
- Linux / UNIX: Reserved Characters And Words
- See also:
- команда file в Linux с примерами
- How to Manipulate Filenames Having Spaces and Special Characters in Linux
- Dealing with file that has dash (-) in it’s name
- Dealing with files having HASH (#) in the name
- Dealing with files having semicolon (;) in its name
- Dealing with other special characters in file/folder name
- Plus Sign (+) in file name
- Dollar sign ($) in file name
- Percent (%) in file name
- Asterisk (*) in file name
- Exclamation mark (!) in file name
- At Sign (@) in file name
- ^ in file name
- Ampersand (&) in file name
- Parentheses () in file name
- Braces <> in file name
- Chevrons <> in file name
- Square Brackets [ ] in file name
- Under score (_) in file name
- Equal-to (=) in File name
- Dealing with back slash (\)
- The Special Case of Forward Slash
- Question Mark (?) in file name
- Dot Mark (.) in file name
- Comma (,) in file name
- Colon (:) in File name
- Having Quotes (single and Double) in file name
- Tilde (
- White Space in file name
- If You Appreciate What We Do Here On TecMint, You Should Consider:
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.
Источник
How to Read a Filename with Spaces in Linux
It’s not very common in Linux to handle filename with spaces but sometimes files copied or mounted from windows would end up with spaces.
While it is not recommended to have file names with spaces, let discuss how to manage filename with spaces in a Linux system.
We will cover how to create, read and copy a file which has spaces in their filename.
1) Creating file names with spaces
To create files with spaces in file names, run the command as shown
For example, to create a file called ‘linoxide docs‘ use the syntax below
Output
If you want to view such a file with space in the file name, use the same principle of enclosing the file names inside the quotation marks.
2) Read a File with spaces in filename
You can use ‘cat’ command or open the document using your preferred text editor such as vim, nano or gedit.
Alternatively, you can use the syntax below
Let’s add some text to the ‘linoxide docs’ file
To view the file execute the command below
Output
3) Creating directory names with spaces
To create directory names with space in between use the syntax below
Please note the space after the backslash
For example, to create a directory called ‘linoxide files‘ run
Output
4) Navigating to a directory with spaces in the directory name
To navigate to a directory with spaces in its directory name, use the syntax below
To navigate to the directory ‘linoxide files’ execute the command below
5) Copying a directory with spaces in the directory name
To copy a directory with spaces in its directory name to a different location use the syntax below
For example to copy ‘linoxide files’ to /home/james path execute
Hope this article explained well on how to manage filename with spaces. Thanks for taking the time to read this article and please leave your comments.
Источник
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:
- All file names are case sensitive. So filename vivek.txt Vivek.txt VIVEK.txt all are three different files.
- 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 в Linux с примерами
Команда file используется для определения типа файла. Тип .file может быть читаемым человеком (например, «текст ASCII») или MIME-типом (например, «text / plain; charset = us-ascii»). Эта команда проверяет каждый аргумент в попытке классифицировать его.
Он имеет три набора тестов следующим образом:
- Тест файловой системы: Этот тест основан на результате, который возвращается из системного вызова stat . Программа проверяет это, если файл пуст или это какой-то особый файл. Этот тест приводит к печати типа файла.
- магический тест: эти тесты используются для проверки файлов с данными в определенных фиксированных форматах.
- языковой тест: этот тест ищет определенные строки, которые могут появляться в любом месте в первых нескольких блоках файла.
Синтаксис:
Пример: команда отображает тип файла
Параметры:
- -b, –brief: используется для отображения только типа файла в кратком режиме.
Синтаксис:
Пример:
Здесь мы видим этот тип файла без имени файла.
* опция: команда отображает тип файла всех файлов.
Вывод показывает все файлы в домашнем каталоге
опция directoryname / *: используется для отображения всех типов файлов файлов в определенном каталоге.
Синтаксис:
Пример:
Вывод показывает все файлы в определенном каталоге.
опция [диапазон] *: для отображения типа файлов в определенном диапазоне.
Синтаксис:
Пример:
Вывод показывает диапазон файлов.
-c опция: вызвать контрольную распечатку проанализированной формы магического файла. Этот параметр обычно используется вместе с флагом -m для отладки нового магического файла перед его установкой.
Пример:
Опция -f: прочитать имена файлов, которые нужно проверить, по имени файла (по одному на строку) перед списком аргументов. Должен присутствовать либо имя файла, либо, по крайней мере, один аргумент имени файла; чтобы проверить стандартный ввод, используйте «-» в качестве аргумента имени файла.
Синтаксис:
-F опция: Файл и тип файла разделяются :. Но мы можем изменить разделитель, используя опцию -F
Синтаксис:
Пример:
Вывод показывает, что файл и типы файлов разделены — и + .
-i опция: для просмотра файла MIME.
Синтаксис:
Пример:
-N опция: не дополняйте имена файлов, чтобы они выровнялись в выходных данных.
Пример:
опция -s: для специальных файлов
Синтаксис:
Пример:
имена файлов: отображает типы файлов нескольких файлов
Синтаксис:
Пример:
Опция -z: Попробуйте заглянуть внутрь сжатых файлов.
Пример:
Опция –help: распечатать справочное сообщение и выйти.
Источник
How to Manipulate Filenames Having Spaces and Special Characters in Linux
We come across files and folders name very regularly. In most of the cases file/folder name are related to the content of the file/folder and starts with number and characters. Alpha-Numeric file name are pretty common and very widely used, but this is not the case when we have to deal with file/folder name that has special characters in them.
Note: We can have files of any type but for simplicity and easy implementation we will be dealing with Text file (.txt), throughout the article.
Example of most common file names are:
Example of numeric file names are:
Example of Alpha-Numeric file names are:
Examples of file names that has special character and is not very common:
One of the most obvious question here is – who on earth create/deal with files/folders name having a Hash (#) , a semi-colon (;) , a dash (-) or any other special character.
I Agree to you, that such file names are not common still your shell should not break/give up when you have to deal with any such file names. Also speaking technically every thing be it folder, driver or anything else is treated as file in Linux.
Dealing with file that has dash (-) in it’s name
Create a file that starts with a dash (-) , say -abx.txt.
Sample Output
The reason for above error, that shell interprets anything after a dash (-) , as option, and obviously there is no such option, hence is the error.
To resolve such error, we have to tell the Bash shell (yup this and most of the other examples in the article is for BASH) not to interpret anything after special character (here dash), as option.
There are two ways to resolve this error as:
You may verify the file thus created by both the above ways by running commands ls or ls -l for long listing.
To edit the above file you may do:
Note: You may replace nano with any other editor of your choice say vim as:
Similarly to move such file you have to do:
and to Delete this file, you have to do:
If you have lots of files in a folder the name of which contains dash, and you want to delete all of them at once, do as:
Important to Note:
1. The same rule as discussed above follows for any number of hypen in the name of the file and their occurrence. Viz., -a-b-c.txt, ab-c.txt, abc-.txt, etc.
2. The same rule as discussed above follows for the name of the folder having any number of hypen and their occurrence, except the fact that for deleting the folder you have to use ‘rm -rf‘ as:
Dealing with files having HASH (#) in the name
The symbol # has a very different meaning in BASH. Anything after a # is interpreted as comment and hence neglected by BASH.
Understand it using examples:
create a file #abc.txt.
Sample Output
The reason for above error, that Bash is interpreting #abc.txt a comment and hence ignoring. So the command touch has been passed without any file Operand, and hence is the error.
To resolve such error, you may ask BASH not to interpret # as comment.
and verify the file just created as:
Now create a file the name of which contains # anywhere except at the begging.
Run ‘ls -l‘ to verify it:
What happens when you create two files (say a and #bc) at once:
Verify the file just created:
Obvious from the above example it only created file ‘a‘ and file ‘#bc‘ has been ignored. To execute the above situation successfully we can do,
and verify it as:
You can move the file as:
You may edit it as using your choice of editor as:
And Delete it as:
To delete all the files that has hash (#) in the file name, you may use:
Dealing with files having semicolon (;) in its name
In case you are not aware, semicolon acts as a command separator in BASH and perhaps other shell as well. Semicolon lets you execute several command in one go and acts as separator. Have you ever deal with any file name having semicolon in it? If not here you will.
Create a file having semi-colon in it.
Sample Output
The reason for above error, that when you run the above command BASH interpret touch as a command but could not find any file operand before semicolon and hence it reports error. It also reports another error that ‘abc.txt‘ command not found, only because after semicolon BASH was expecting another command and ‘abc.txt‘, is not a command.
To resolve such error, tell BASH not to interpret semicolon as command separator, as:
Note: We have enclosed the file name with single quote » . It tells BASH that ; is a part of file name and not command separator.
Rest of the action (viz., copy, move, delete) on the file and folder having semicolon in its name can be carried out straight forward by enclosing the name in single quote.
Dealing with other special characters in file/folder name
Plus Sign (+) in file name
Don’t requires anything extra, just do it normal way, as simple file name as shown below.
Dollar sign ($) in file name
You have to enclose file name in single quote, as we did in the case of semicolon. Rest of the things are straight forward..
Percent (%) in file name
You don’t need to do anything differently, treat it as normal file.
Asterisk (*) in file name
Having Asterisk in file name don’t change anything and you can continue using it as normal file.
Note: When you have to delete a file that starts with * , Never use following commands to delete such files.
Exclamation mark (!) in file name
Just Enclose the file name in single quote and rest of the things are same.
At Sign (@) in file name
Nothing extra, treat a filename having At Sign as nonrmal file.
^ in file name
No extra attention required. Use a file having ^ in filename as normal file.
Ampersand (&) in file name
Filename should be enclosed in single quotes and you are ready to go.
Parentheses () in file name
If the file name has Parenthesis, you need to enclose filename with single quotes.
Braces <> in file name
No Extra Care needed. Just treat it as just another file.
Chevrons <> in file name
A file name having Chevrons must be enclosed in single quotes.
Square Brackets [ ] in file name
Treat file name having Square Brackets as normal files and you need not take extra care of it.
Under score (_) in file name
They are very common and don’t require anything extra. Just do what you would have done with a normal file.
Equal-to (=) in File name
Having an Equal-to sign do not change anything, you can use it as normal file.
Dealing with back slash (\)
Backslash tells shell to ignore the next character. You have to enclose file name in single quote, as we did in the case of semicolon. Rest of the things are straight forward.
The Special Case of Forward Slash
You cannot create a file the name of which includes a forward slash (/) , until your file system has bug. There is no way to escape a forward slash.
So if you can create a file such as ‘/12.txt’ or ‘b/c.txt’ then either your File System has bug or you have Unicode support, which lets you create a file with forward slash. In this case the forward slash is not a real forward slash but a Unicode character that looks alike a forward slash.
Question Mark (?) in file name
Again, an example where you don’t need to put any special attempt. A file name having Question mark can be treated in the most general way.
Dot Mark (.) in file name
The files starting with dot (.) are very special in Linux and are called dot files. They are hidden files generally a configuration or system files. You have to use switch ‘-a‘ or ‘-A‘ with ls command to view such files.
Creating, editing, renaming and deleting of such files are straight forward.
Note: In Linux you may have as many dots (.) as you need in a file name. Unlike other system dots in file name don’t means to separate name and extension. You can create a file having multiple dots as:
and check it as:
Comma (,) in file name
You can have comma in a file name, as many as you want and you Don’t requires anything extra. Just do it normal way, as simple file name.
Colon (:) in File name
You can have colon in a file name, as many as you want and you Don’t requires anything extra. Just do it normal way, as simple file name.
Having Quotes (single and Double) in file name
To have quotes in file name, we have to use the rule of exchange. I.e, if you need to have single quote in file name, enclose the file name with double quotes and if you need to have double quote in file name, enclose it with single quote.
Tilde (
Some Editors in Linux like emacs create a backup file of the file being edited. The backup file has the name of the original file plus a tilde at the end of the file name. You can have a file that name of which includes tilde, at any location simply as:
White Space in file name
Create a file the name of which has space between character/word, say “hi my name is avishek.txt”.
It is not a good idea to have file name with spaces and if you have to distinct readable name, you should use, underscore or dash. However if you have to create such a file, you have to use backward slash which ignores the next character to it. To create above file we have to do it this way..
I have tried covering all the scenario you may come across. Most of the above implementation are explicitly for BASH Shell and may not work in other shell.
If you feel that I missed something (that is very common and human nature), you may include your suggestion in the comments below. Keep Connected, Keep Commenting. Stay Tuned and connected! Like and share us and help us get spread!
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник