- Windows — Unix Text Converter 1.0
- Преобразование окончаний строк Unix в Windows
- 12 ответов
- Indiana University Indiana University Indiana University
- Convert between Unix and Windows text files
- Overview
- Related documents
- How To Convert Files from Linux/Unix Format to Windows and Vice Versa
- Converting Files from Linux/UNIX format to Windows Format
- The dos2unix and unix2dos command
- The awk command
- The tr command
- Using the Visual Editor (Vi)
- Using File Transfer Protocol Programs
- Conclusion
- How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script
- 22 Answers 22
Windows — Unix Text Converter 1.0
Программа предназначена для преобразования символов перехода строки (перевода каретки) Windows в символы перехода строки (перевода каретки) Unix-подобных операционных систем и обратно и будет полезна для веб-разработчиков, а также пользователям, которые закачивают файлы на сервер через панель управления сайтом.
Помимо преобразования отдельных файлов программа может преобразовывать все файлы в указанной папке включая все вложенные папки. При этом имеется возможность игнорировать бинарные файлы и преобразовывать только файлы, которые содержат исключительно текстовые символы. В данном случае под бинарными файлами подразумеваются все файлы, в которых встречается хотя бы один символ из следующего набора символов:
Символы с кодом от 0 до 8 включительно;
Символы с кодом 11 и 12;
Символы с кодом от 14 до 31 включительно;
Все остальные файлы считаются текстовыми.
Например, для обеспечения нормальной работы скриптов на Linux сервере вам нужно преобразовать в какой-либо папке во всех скриптах и файлах которые они используют символы перехода строки Windows в символы перехода строки Linux, но при этом нельзя изменять файлы рисунков. Для ля того, чтобы преобразовать все файлы, содержащие только текстовые символы, запустите программу Windows — Unix Text Converter, проверьте, что стоит галочка напротив «Не изменять бинарные файлы», выберите пункт меню «Конвертировать папку Windows В Unix», появится диалог выбора каталога, выберите папку, файлы в которой нужно преобразовать, после подтверждения все символы перехода на новую строку Windows в файлах в указанной папке и всех её подпапках будут преобразованы в символы перехода на новую строку Linux.
Специализированные FTP клиенты, предназначенные для загрузки файлов выполняют эту функцию автоматически если указаны соответствующие пункты в настройках. Но даже пользуясь FTP клиентом, разработчикам очень часто приходится сталкиваться с подобной проблемой, например, вы загрузили на свой компьютер архив со скриптами, которые вы хотите установить на свой сайт, и некоторые из них вам нужно отредактировать. С символами перевода каретки Linux эти файлы будут выглядеть очень трудно читаемыми в текстовом редакторе. Но этой проблемы можно избежать, воспользовавшись данной программой, преобразовав символы перевода каретки Unix в символы перевода каретки Windows. Для установки программы просто распакуйте содержимое архива в любую удобную для вас папку.
Преобразование окончаний строк Unix в Windows
Недавно я вернулся в Windows из Linux. У меня есть файлы с CRLF, некоторые с LF и некоторые из них смешанные. Есть ли утилита, которая поможет мне найти все мои файлы, связанные с Unix, и преобразовать их в соответствующие файлы с завершенным CRLF?
Утилита должна работать в Windows, а не в Linux. Я уже переехал. Я бы предпочел не устанавливать Cygwin , если я могу его избежать.
12 ответов
Вы можете конвертировать их с помощью утилиты unix2dos на вашей платформе Linux. Существуют версии unix2dos для Windows .
Если у вас установлен Perl, вы также можете использовать этот один вкладыш:
Вот простой и быстрый способ.
Перетащите текстовый файл в Chrome (я не знаю других браузеров), а затем вырезаем и вставляем обратно в исходный файл:)
Например: sfk addcr -dir . -file .txt -norec
изменяет LF-окончания в CR /LF для Windows, на всех .txt-файлах текущего каталога, но НЕ внутри подкаталогов (без рекурсии).
Но эта программа намного больше, чем просто.
В Cygwin вы можете конвертировать между файлами Unix и DOS AKA Windows с помощью двух встроенных утилит:
Преобразование в формат DOS CR /LF:
Преобразуйте обратно в формат Unix CR:
Файл остается на месте с тем же именем.
Я собираюсь бросить это решение там. Гит сделает это. Смотрите это сообщение
Итак, теоретически вы можете сделать это для преобразования всего дерева
Измените crlf на lf , если вы хотите пойти в другую сторону. ПРИМЕЧАНИЕ: вы еще не закончили, продолжайте читать
Введите git status , чтобы увидеть, какие файлы будут затронуты. Возможно, вам придется добавить строки, например
и т. д. до .gitattributes , чтобы избежать преобразования определенных файлов. Вы также можете указать определенные файлы как текст
Затем просто повторите эти 2 строки после редактирования .gitattributes
Затем снова используйте git status , чтобы узнать, какие файлы будут изменены. Когда вы уверены, что все файлы, которые вы хотите затронуть, перечислены в git status , а затем зафиксируйте
теперь проверьте все файлы снова
Теперь у них должно быть все, что у вас есть,
** ПРИМЕЧАНИЕ. Если вы уже использовали git, пропустите первые три команды git. Если вы не использовали git, теперь вы можете удалить файл .gitattributes и .git .
** Резервное копирование файлов: git rm —cached -r удаляет их все (хотя они теоретически в вашем git repo (папка .git ), так как они восстанавливаются с помощью последней команды git reset —hard . Просто, поскольку файлы удаляются, лучше всего их резервировать.
В моем дистрибутиве Linux есть две небольшие утилиты: fromdos и todos , которые я использую для этой задачи.
Используйте текстовый редактор, который понимает оба конца строки, например SciTE или Notepad ++ , если вам не нужно преобразовывать всю строку, заканчивающуюся во всех ваших файлах, но просто не хотите видеть весь файл сгруппирован в первую строку.
Существует много способов перевода символов eoln в файлы TEXT, и у каждого есть любимый.
Но я всегда переношу файлы с Linux на Windows в режиме BINARY, затем открываю файлы TEXT в Windows с помощью редактора, способного открывать оба типа, и при необходимости сохранять их в любой форме.
Я использовал редактор файлов Programmers для этого, но Notepad ++ тоже может это сделать. WordPad также полезен [по крайней мере, для просмотра файлов с завершенным LF].
Я думаю о простых текстовых файлах, которые могут возникнуть в Linux, и их нужно читать в стандартном (стандартном) мире Windows. Я не уверен, что вы имели в виду под «unix-touched files».
Чтобы предложить дополнительные параметры (хотя мне больше всего понравился запрос пользователя user45832 ):
Онлайн-преобразователи
Пакетный /DOS однострочный (удаляет пустые строки) :
Powershell:
Получил последние два отсюда
Преобразование окончаний строки Unix в конец строки Windows:
Преобразование окончаний строк Windows в конец строки Unix:
Старые версии awk не включают sub . В таких случаях используйте ту же команду, но замените awk на gawk или nawk .
В Википедии есть решение в cmd:
В PowerShell существуют различные способы сделать это, изменив то, что было сделано в на этом вопросе .
Это также можно сделать в VBScript и JScript , которые также являются инструментами, которые уже доступны в Windows без установки стороннего приложения.
Я использовал, чтобы открыть файл в ‘edit’ и сохранить, поскольку это было выполнено .
Indiana University Indiana University Indiana University
Convert between Unix and Windows text files
Overview
The format of Windows and Unix text files differs slightly. In Windows, lines end with both the line feed and carriage return ASCII characters, but Unix uses only a line feed. As a consequence, some Windows applications will not show the line breaks in Unix-format files. Likewise, Unix programs may display the carriage returns in Windows text files with Ctrl-m ( ^M ) characters at the end of each line.
There are many ways to solve this problem. This document provides instructions for using FTP, screen capture, unix2dos and dos2unix, tr , awk , Perl, and vi to do the conversion. To use these utilities, the files you are converting must be on a Unix computer.
When using an FTP program to move a text file between Unix and Windows, be sure the file is transferred in ASCII format, so the document is transformed into a text format appropriate for the host. Some FTP programs, especially graphical applications, do this automatically. If you are using command line FTP, before you begin the transfer, enter:
You can use tr to remove all carriage returns and Ctrl-z ( ^Z ) characters from a Windows file:
However, you cannot use tr to convert a document from Unix format to Windows.
To use awk to convert a Windows file to Unix, enter:
To convert a Unix file to Windows, enter:
Older versions of awk do not include the sub function. In such cases, use the same command, but replace awk with gawk or nawk .
To convert a Windows text file to a Unix text file using Perl, enter:
To convert from a Unix text file to a Windows text file, enter:
You must use single quotation marks in either command line. This prevents your shell from trying to evaluate anything inside.
In vi, you can remove carriage return ( ^M ) characters with the following command:
To input the ^M character, press Ctrl-v , and then press Enter or return .
In vim, use :set ff=unix to convert to Unix; use :set ff=dos to convert to Windows.
Related documents
This is document acux in the Knowledge Base.
Last modified on 2019-12-17 14:27:06 .
How To Convert Files from Linux/Unix Format to Windows and Vice Versa
If you’ve ever transferred a text file from a UNIX based system to a Windows system directly, you know that when you open the text file on the Windows system, it is usually not displayed correctly. Windows based text reader programs (like Notepad) may not be able to display the text. In most cases, when you open the text file, all the words get displayed on a single giant line, without any breaks. This is because there is a slight difference in the way a text document is written (and read) on Windows and UNIX.
If a file was written on a Windows based system and is opened by a text editor on a UNIX system, it is very common for the “Ctrl-M” characters (^M) to be displayed at the end of each line of text. If a file was written on a UNIX system and opened by a text editor on a Windows system, the line break character (EOL) may not be displayed correctly. The carriage return character is also different for both UNIX and Windows.
While dealing with files, you don’t want to be limited by whether the file was created on Linux or Windows. So how do you convert a file from UNIX to Windows (or vice versa) without having the formatting go all crazy? We’ll walk you through the steps.
Converting Files from Linux/UNIX format to Windows Format
If you’re using a UNIX based system to transfer the files to a Windows system, there are some commands that let you convert the text file(s) you are transferring to a format Windows can understand.
The dos2unix and unix2dos command
You can use command line to safely convert files from UNIX to Windows and vice versa. To convert a Windows text file to a UNIX text file, enter this:
The above command converts and replaces “windows.txt” file to “unix.txt”. To convert a UNIX text file to a Windows text file, enter this command:
The above command will convert a UNIX created text file called “unix.txt” to a Windows compatible text file called “windows.txt”.
The awk command
The awk command also lets you convert a file from UNIX to Windows and vice versa. To convert a Windows file to a UNIX file, enter the following command:
To convert a UNIX text file called “unix.txt” to a Windows text file called “windows.txt”, enter the following command:
The tr command
The tr command (transliterate) can be used to remove the carriage return characters and the “Ctrl-Z” characters from a Windows file. This can only be done if you are converting a file from Windows to UNIX. The command will be written as follows:
The tr command transliterates one character with another. In this case, it is helping you omit unnecessary characters.
Using the Visual Editor (Vi)
If you are using the Visual Editor to view a file created on a Windows system, you can remove the carriage return characters by typing the following command line:
To get the computer to input the ^M character, you need to hit “Ctrl + v” and then press Return.
Using File Transfer Protocol Programs
File Transfer Protocol (FTP) programs are available both for UNIX and Windows system. If you need to convert a lot of files from Windows to UNIX (or the other way around), then it’s a good idea to download a FTP program. There are many available for free on the Internet. The Hummingbird FTP is one of the more popular FTP programs out there. It is secure and easy to use.
Most FTP programs will transfer files from UNIX to Windows in the ASCII format. Sometimes you have to specify the format for yourself (if you are using command line based FTP programs). To do that, just enter this in the command line:
Conclusion
The easiest way to convert a file from a UNIX format to Windows (and the other way around) is to use an FTP program. The conversion commands are your next best bet. If you are looking for additional commands that perform the same task, you can search for perl and sed commands. However, do keep in mind that these commands may not work across all systems.
I’m a techie with over a decade of programming experience, spread across a wide range of interesting, path breaking technologies. Now I’m sharing my passion for technology, and making tech easier, with everyone! Hope you enjoy reading about, and playing with technology, as much as I do!
How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script
How can I programmatically (i.e., not using vi ) convert DOS/Windows newlines to Unix?
The dos2unix and unix2dos commands are not available on certain systems. How can I emulate these with commands like sed , awk , and tr ?
22 Answers 22
You can use tr to convert from DOS to Unix; however, you can only do this safely if CR appears in your file only as the first byte of a CRLF byte pair. This is usually the case. You then use:
Note that the name DOS-file is different from the name UNIX-file ; if you try to use the same name twice, you will end up with no data in the file.
You can’t do it the other way round (with standard ‘tr’).
If you know how to enter carriage return into a script ( control-V , control-M to enter control-M), then:
where the ‘^M’ is the control-M character. You can also use the bash ANSI-C Quoting mechanism to specify the carriage return:
However, if you’re going to have to do this very often (more than once, roughly speaking), it is far more sensible to install the conversion programs (e.g. dos2unix and unix2dos , or perhaps dtou and utod ) and use them.
If you need to process entire directories and subdirectories, you can use zip :
This will create a zip archive with line endings changed from CRLF to CR. unzip will then put the converted files back in place (and ask you file by file — you can answer: Yes-to-all). Credits to @vmsnomad for pointing this out.