How to convert files from Dos to Unix
Asked Answered
O

5

9

I am having several files which I want to convert from Dos to Unix. Is there any API or method which will help me to do this?

Overcasting answered 21/2, 2012 at 9:24 Comment(1)
E
23

There are linux tools that can do this (dos2unix for example).

In Java it can be done with String.replaceAll().

DOS uses \r\n for line termination, while UNIX uses a single \n.

String unixText = windowsText.replaceAll("\r\n", "\n"); // DOS2UNIX

So no, no API exists. Yes, it is dead easy.

Endless answered 21/2, 2012 at 9:29 Comment(2)
Do i need to open all files one by one and replaceAll("\r\n", "\n").Overcasting
Yes, of course. Please also note that this only makes sense for ASCII text files!Endless
S
2

There is a utility/command in Linux/Unix called dos2unix that will help you convert your files from dos to unix format. To install simply type in console(you may need root privileges)

yum install dos2unix

To do the conversion you have to use command dos2unix followed by filename. For example

[aniket@localhost ~]$ dos2unix sample.txt 
dos2unix: converting file sample.txt to UNIX format ...

For all files in a directory you can simply use

dos2unix *
Syracuse answered 19/7, 2013 at 13:6 Comment(2)
I don't know why this answer was down-voted. It did, after all, indicate the package name to use when installing from yum, which none of the other answers noted.Widower
@GarretWilson Because that is not Java as stated in the tags (hello from the future :D )Afferent
S
2

Just an alternate way (than the one parasietje described) using dox2unix. Say you all dos files are in one folder

Runtime.getRuntime().exec("dos2unix /path/to/dos/files/*");
Shoshana answered 19/7, 2013 at 13:25 Comment(0)
B
1

Most unix/linux distributions have utility named unix2dos and dos2unix commands.

EDIT: Just copy your file to unix machine and run dos2unix *.

You can also find this utility for Windows and do the same.

Bucher answered 21/2, 2012 at 9:29 Comment(0)
L
1
String unixText = windowsText.replaceAll("\r\n", "\n"); // DOS2UNI

The above line should remove all \r but for some reason it also removes the \n so I had to add it back when printing unixText to a file: unixText + "\n"

Lazes answered 30/1, 2016 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.