- Команда file в Linux
- Синтаксис и опции file
- Примеры использования file
- Выводы
- DOS to Unix: Commands and Examples
- Converting Files on Linux
- Option 1: Converting DOS to UNIX with dos2unix Command
- Option 2: Converting UNIX to DOS using the unix2dos Command
- Option 3: Using the sed Command
- Option 4: Using the tr Command
- Option 5: Using the Vim Text Editor
- Option 6: Using a Perl One Liner
- Example: Converting a Sample File from DOS to Unix Format
- Recursively rename files (change extension) in Linux
- 7 Answers 7
- Explanation
Команда file в Linux
Команда file — одна из самых полезных, поскольку позволяет узнать тип данных, которые на самом деле содержатся внутри документа. Если у вас есть какой-либо файл, взятый из ненадёжного источника, не поленитесь проверить его с помощью этой команды, прежде чем нажать кнопку Открыть. Возможно, такая предосторожность покажется лишней, но она оградит вас от «встречи» с нежелательным контентом.
В большинстве дистрибутивов Linux утилита file (работу которой и запускает одноимённая команда) входит в стандартный набор программного обеспечения.
Синтаксис и опции file
Синтаксис команды file достаточно простой. Записывать её в эмуляторе терминала или консоли следует так:
file опции название_документа
Что же касается опций, то их у этой команды несколько десятков. Мы рассмотрим лишь основные:
- -b, —brief — запрет на демонстрацию имен и адресов файлов в выводе команды;
- -i, —mime — определение MIME-типа документа по его заголовку;
- —mime-type, —mime-encoding — определение конкретного элемента MIME;
- -f, —files-from — анализ документов, адреса которых указаны в простом текстовом файле;
- -l, —list — список паттернов и их длина;
- -s, —special-files — предотвращение проблем, которые могут возникнуть при чтении утилитой специальных файлов;
- -P — анализ определенной части файла, которая обозначается различными параметрами;
- -r, —raw — отказ от вывода /ooo вместо непечатных символов;
- -z — анализ содержимого сжатых документов.
Для того, чтобы ознакомиться с полным списком опций, выполните в терминале команду:
Примеры использования file
Если вам нужно всего лишь посмотреть тип файла, использовать опции не обязательно. Достаточно прописать имя команды, а также название файла и путь к нему, при условии, что он находится не в корневой папке:
Случается, что нужно проверить не один, а несколько файлов. Чтобы не выполнять команду много раз подряд, перечисляйте названия всех файлов через пробел:
file /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff
Как видно на примере, картинки с расширениями gif и tiff в действительности оказались текстовыми документами, а архив с расширением zip — PDF документом. Кстати, команда file даёт возможность не только проверить, является ли архив архивом, но и заглянуть внутрь, чтобы узнать, что в нём содержится. Для этой цели используется опция -z:
file -z /home/main-user/losst/testarchive.zip
Как вы успели заметить, команда, возвращая ответ, постоянно выводит названия файлов, что в некоторых случаях бывает удобно, но зачастую только усложняет чтение результатов. Отключить эту функцию легко — воспользуйтесь опцией -b:
file -b /home/main-user/losst/test-file.gif /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff
Иногда нужно узнать не просто тип файла, а его MIME-тип. В таком случае на помощь приходит опция -i:
file -i -b /home/main-user/losst/fileA.sbin /home/main-user/losst/fileG.aspx /home/main-user/losst/fileH.lua
Нередко по каким-либо причинам утилита не может найти указанный файл: например, вы ошиблись буквой в его названии или неверно указали папку, в которой он находится. Тогда вывод информации об этом файле предваряет фраза cannot open. Впрочем, есть возможность видоизменить результат, добавив в него сообщение об ошибке. Для этого используйте опцию -E.
Сравните вывод команды с опцией -E и без неё:
file -E -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif
file -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif
Еще один способ работы с утилитой file — запись названий и адресов документов в простой текстовый файл. Применяя этот способ на практике, не забывайте добавлять к команде опцию —files-from, после которой указывайте имя файла, содержащего список документов, и путь к нему.
file —files-from /home/main-user/losst/list_of_files.txt
Выводы
Команда file помогает избежать ситуаций, когда вам приходится открывать подозрительные файлы, не будучи уверенными в их содержимом. Также вы можете использовать её для проверки содержимого нескольких архивов, если есть необходимость найти потерявшийся в большом массиве файлов документ, но нет желания просматривать все архивы вручную.
Источник
DOS to Unix: Commands and Examples
Home » SysAdmin » DOS to Unix: Commands and Examples
Files created in DOS/Windows use carriage return (\r) and line feed (\n) for line endings. However, files in Unix/Linux solely use line feed.
Therefore, when transferring a file from one system to another, make sure to convert the files.
In this tutorial, you will learn how to transfer files from DOS to Unix and vice-versa.
Converting Files on Linux
There are several ways you can transfer files to use the appropriate line endings. Convert the files using the:
- dos2unix command
- unix2dos command
- sed command
- tr command
- Vi/Vim text editor (see Vim commands cheat sheet)
- perl one-liner command
Option 1: Converting DOS to UNIX with dos2unix Command
The simplest way to convert line breaks in a text file is to use the dos2unix tool.
Install the tool by running the command:
If you download a file created in DOS/Windows onto your Linux system, you can convert it using the dos2unix command:
The command converts the file without saving it in the original format. If you want to save the original file, add the -b attribute before the file name. Doing so creates a backup file under the same name and the .bak extension.
Option 2: Converting UNIX to DOS using the unix2dos Command
To convert a file created on a Linux system into the DOS format, run the command:
Alternatively, add the -b attribute to save the original file as backup:
Option 3: Using the sed Command
You can also use the sed (stream editor) command to remove the carriage return line endings. The command syntax to do so is:
Instead of just typing ^M , press Ctrl+V followed by Ctrl+M to enter the carriage return symbol. When using the sed command, specify the name of the DOS file [original_file_name] and how you want to name the converted file [converted_file_name] .
To change the file format from Unix to DOS, use the command:
Option 4: Using the tr Command
Another way to convert a file into the Unix format is to remove \r line endings with the tr command. The tr command is a command line utility for translating or deleting characters.
Use the command in the following format:
Option 5: Using the Vim Text Editor
You can also remove carriage return line endings from files in DOS format using the Vi/Vim text editor.
Open the file in Vi/Vim:
Then press : and type in the following Vi/Vim command (making sure you type Ctrl+V then Ctrl+m instead of ^m ):
Option 6: Using a Perl One Liner
Lastly, you can use a Perl one-liner command to delete all \r line endings. Pearl on-liners are scripts that fit in a single line of code.
To replace all carriage return and line feed endings with just line feeds:
1. Open the file in the Vi/Vim text editor.
2. Press : to prompt the command line.
3. Type in the following command and press Enter:
You should see the the changes in the file right away.
Note: Need help finding files on your Linux system? Take a look at how to use the find command or how to show hidden files in Linux.
Example: Converting a Sample File from DOS to Unix Format
Let’s say you downloaded a file named sample-dos-file.
By opening the file using the Vim/Vi text editor, you would see that after each line ending there is ^M (a carriage return).
Another way to see the file uses both carriage return and line feed for line endings is to view the file in octal values.
To do so, run the command:
The output displays the content of the file with its octal values, as in the image below. You can see that each line end is marked with the octal values 015 (\r) and 012 (\n).
Now, to convert the file and remove all carriage return endings, you would run the command:
Open the same file in Vim/Vi. It doesn’t include any ^M symbols signaling the line ending.
To confirm the file is in Unix format, you can also open view the content in octal values. The output should display just the 012 values for \n.
This article showed six ways to convert a DOS file into a Unix format and vice versa.
The simplest and recommended way is using the dos2unix command. If you cannot utilize dos2unix , you have five other options to choose from.
Источник
Recursively rename files (change extension) in Linux
How do I rename all files in a directory, recursively, changing one file extension to another, for thousands of files in thousands of subfolders? I see a lot of commands that do almost what I want, but not quite.
7 Answers 7
of course remove the -v when actually doing it, or it will waste time displaying all the files
Remove the -n to actually perform the renaming.
Explanation
The above starts walking the directory tree starting at the current working directory ( . ). Every time a file name matches the pattern *.andnav (e.g., foo.andnav ) the following command is executed:
Where $0 is foo.andnav and $<0%.andnav>.tile replaces the .andnav suffix with .tile so basically:
I found this method is easier and easier to read:
At least on Ubuntu derivations rename takes a list of files from STDIN if none are on the command line. And this can be tested easily with:
until you get it right.
find -execdir rename
https://superuser.com/a/213146/128124 works directly only for suffixes, but this will work for arbitrary regex replacements on basenames:
or to affect files only:
-execdir first cd s into the directory before executing only on the basename.
Tested on Ubuntu 20.04, find 4.7.0, rename 1.10.
Convenient and safer helper for it
Sample usage to replace spaces ‘ ‘ with hyphens ‘-‘.
Dry run that shows what would be renamed to what without actually doing it:
Command explanation
The awesome -execdir option does a cd into the directory before executing the rename command, unlike -exec .
-depth ensure that the renaming happens first on children, and then on parents, to prevent potential problems with missing parent directories.
-execdir is required because rename does not play well with non-basename input paths, e.g. the following fails:
The PATH hacking is required because -execdir has one very annoying drawback: find is extremely opinionated and refuses to do anything with -execdir if you have any relative paths in your PATH environment variable, e.g. ./node_modules/.bin , failing with:
find: The relative path ‘./node_modules/.bin’ is included in the PATH environment variable, which is insecure in combination with the -execdir action of find. Please remove that entry from $PATH
-execdir is a GNU find extension to POSIX. rename is Perl based and comes from the rename package.
Rename lookahead workaround
If your input paths don’t come from find , or if you’ve had enough of the relative path annoyance, we can use some Perl lookahead to safely rename directories as in:
I haven’t found a convenient analogue for -execdir with xargs : Xargs: change working directory to file path before executing?
The sort -r is required to ensure that files come after their respective directories, since longer paths come after shorter ones with the same prefix.
Источник