How to convert Windows end of line in Unix end of line (CR/LF to LF)
I’m a Java developer and I’m using Ubuntu to develop. The project was created in Windows with Eclipse and it’s using the Windows-1252 encoding.
To convert to UTF-8 I’ve used the recode program:
This command gives this error:
Convert line endings from CR/LF to a single LF: Edit the file with Vim, give the command :set ff=unix and save the file. Recode now should run without errors.
Nice, but I’ve many files to remove the CR/LF character from, and I can’t open each to do it. Vi doesn’t provide any option to command line for Bash operations.
Can sed be used to do this? How?
8 Answers 8
There should be a program called dos2unix that will fix line endings for you. If it’s not already on your Linux box, it should be available via the package manager.
sed cannot match \n because the trailing newline is removed before the line is put into the pattern space, but it can match \r , so you can convert \r\n (DOS) to \n (Unix) by removing \r:
Warning: this will change the original file
However, you cannot change from Unix EOL to DOS or old Mac ( \r ) by this. More readings here:
Actually, Vim does allow what you’re looking for. Enter Vim, and type the following commands:
The first of these commands sets the argument list to every file matching **/*.java , which is all Java files, recursively. The second of these commands does the following to each file in the argument list, in turn:
- Sets the line-endings to Unix style (you already know this)
- Writes the file out iff it’s been changed
- Proceeds to the next file
The tr command can also do this:
and should be available to you.
You’ll need to run tr from within a script, since it cannot work with file names. For example, create a file myscript.sh:
Running myscript.sh would process all the java files in the current directory and its subdirectories.
I’ll take a little exception to jichao’s answer. You can actually do everything he just talked about fairly easily. Instead of looking for a \n , just look for carriage return at the end of the line.
To change from Unix back to DOS, simply look for the last character on the line and add a form feed to it. (I’ll add -r to make this easier with grep regular expressions.)
Theoretically, the file could be changed to Mac style by adding code to the last example that also appends the next line of input to the first line until all lines have been processed. I won’t try to make that example here, though.
Warning: -i changes the actual file. If you want a backup to be made, add a string of characters after -i . This will move the existing file to a file with the same name with your characters added to the end.
Ошибка: Some are Mac OS X (UNIX) and some are Windows
Написать программу на Си под unix (вывод, ip, маски, широковещательного адреса, mac)
Всем привет! Ребята помогите! Нужно написать программу которая выводит ip адрес, маску.
error C4335: Обнаружен файл в формате Mac: преобразуйте исходный файл в формат DOS или UNIX
Есть программа: //24. Удалить из каждой строки слова, длина которых равна к. #include.
Возможно ли установить Windows новее Windows XP с флешки на Mac mini?
Здравствуйте, у меня вот такой вопрос,у меня комп mac mini но чуть больше года назад пришлось.
Установка windows на mac book: загрузочного диска windows 8 не видно
здраствуйте. у меня такая проблема.. есть mac book и на нем установлена windows 7. мне нужно.
Решение
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Не запускается Windows 10 (на iMac с установленными Mac OS и Windows 10)
Доброго времени суток. Есть iMac с установленным на него Windows 10. Как давно не знаю, так как.
Windows 7 + Unix
Всех с наступающим! Возможно ли установить unix в качестве второй ОС, если на машине уже.
Эмуляция ОС Unix в Windows
Если честно, не знал, в какой раздел поместить тему. Поместил сюда. Подскажите, как написать.
Работа в Unix из под Windows
Имеется Windows система. Мне нужно разобраться в unix. Ставить ее не хочу. Посоветуйте где и.
UNIX формат под Windows
Суть: Надо настраивать много роутеров, меняется в конфигурации (файл config1.dat) только пароль(361.
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.