简体   繁体   中英

Replacing newline character in UNIX

I'm making a code to replace a newline character from a string. On Windows, when I use

String.replaceAll(System.getProperty("line.separator"), "\\n");

this works fine, but it fails in UNIX.

What should i use in UNIX ?

\\n is correct for Unix. Windows uses \\r\\n and Mac uses \\r IIRC.

The problem may lie in the fact that Java, being a multiplatform language, automatically replaces \\n with the system's separator. I don't know Java but I assume this is the case.

Edit: If the code you posted is what you're using, I think I see the problem. String is a class. It is also immutable in Java. It should instead be this:

String myStr = "abc\ndef";
myStr = myStr.replaceAll(/* params */);

The text being received probably contained windows line separators, so replacing just the \\n character had no effect.

If you don't know the origin of the text (or the text contains a mixture of line separators), the following approach can help. First convert windows and mac line separators into unix separators, then convert the unix separators to the system separator.

final String DOS = "\r\n", NIX = "\n", MAC = "\r";
String converted = original.replace(DOS, NIX)
                           .replace(MAC, NIX)
                           .replace(NIX, System.lineSeparator());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM