Символ переноса строки windows linux

Difference between CR LF, LF and CR line break types

I’d like to know the difference (with examples if possible) between CR LF (Windows), LF (Unix) and CR (Macintosh) line break types.

Very similar, but not an exact duplicate. \n is typically represented by a linefeed, but it’s not necessarily a linefeed.

CR and LF are ASCII and Unicode control characters while \r and \n are abstractions used in certain programming languages. Closing this question glosses over fundamental differences between the questions and perpetuates misinformation.

@AdrianMcCarthy It’s a problem with the way close votes act as answers in a way; an answer claiming the two were the same could be downvoted and then greyed out as very, very wrong, but it only takes 4 agreeing votes (comparable to upvotes) to have a very wrong close happen, with no way to counter the vote until after it’s happened.

This formulation of the question is admittedly better, but it is still for all practical purposes the same question.

10 Answers 10

CR and LF are control characters, respectively coded 0x0D (13 decimal) and 0x0A (10 decimal).

They are used to mark a line break in a text file. As you indicated, Windows uses two characters the CR LF sequence; Unix (and macOS starting with Mac OS X 10.0) only uses LF; and the classic Mac OS (before 10.0) used CR.

An apocryphal historical perspective:

As indicated by Peter, CR = Carriage Return and LF = Line Feed, two expressions have their roots in the old typewriters / TTY. LF moved the paper up (but kept the horizontal position identical) and CR brought back the «carriage» so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF was doing both, i.e., preparing to type a new line. As time went by the physical semantics of the codes were not applicable, and as memory and floppy disk space were at a premium, some OS designers decided to only use one of the characters, they just didn’t communicate very well with one another 😉

Most modern text editors and text-oriented applications offer options/settings, etc. that allow the automatic detection of the file’s end-of-line convention and to display it accordingly.

so actually Windows is the only OS that uses these characters properly, Carriage Return, followed by a Line Feed.

Would it be accurate, then, to say that a text file created on Windows is the most compatible of the three i.e. the most likely to display on all three OS subsets?

@Hashim it might display properly but trying to run a textual shell script with carriage returns will usually result in an error

Rolf — that statement assumes that keeping old terminology/technology in new technology is correct. CRLF = 2 bytes. CR = 1, LF = 1. With as often as they are used, that actually translates to a huge amount of data. Once again, Windows has chosen to be different from the entirety of the *NIX world.

Читайте также:  Install samba server in linux

This is a good summary I found:

The Carriage Return (CR) character ( 0x0D , \r ) moves the cursor to the beginning of the line without advancing to the next line. This character is used as a new line character in Commodore and early Macintosh operating systems (Mac OS 9 and earlier).

The Line Feed (LF) character ( 0x0A , \n ) moves the cursor down to the next line without returning to the beginning of the line. This character is used as a new line character in Unix-based systems (Linux, Mac OS X, etc.)

The End of Line (EOL) sequence ( 0x0D 0x0A , \r\n ) is actually two ASCII characters, a combination of the CR and LF characters. It moves the cursor both down to the next line and to the beginning of that line. This character is used as a new line character in most other non-Unix operating systems including Microsoft Windows, Symbian and others.

The «vertical tab»-character moves the cursor down and keep the position in the line, not the LF-character. The LF is EOL.

@Vicrobot Developers will often split a string or perform other operations with the exact sequence \r\n , so \n\r would not match. Also one would think that text editors also treat the two characters as one sequence and don’t separatly go «oh, now I have to go down one line» and «oh, now I have to move to the front». Were it so then yes, you could freely swap the order around

It’s really just about which bytes are stored in a file. CR is a bytecode for carriage return (from the days of typewriters) and LF similarly, for line feed. It just refers to the bytes that are placed as end-of-line markers.

There is way more information, as always, on Wikipedia.

I think it’s also useful to mention that CR is the escape character \r and LF is the escape character \n . In addition, Wikipedia:Newline.

In Simple words CR and LF is just end of line and new line according to this link , is this correct ?

@shaijut CR stands for Carriage Return. That was what returned the carriage on typewriters. So, mostly correct.

The superior LFCR option is sadly missing. Its benefit is that by doing the Line Feed first, the Selectric golfball can’t smear the just printed line with still fresh ink upon executing the Carriage Return

Actually, it’s not a typewriter but «teletype», old computer client terminals with mechanical print heads and paper, where CR/LF were required for computers to behave properly. If you just did CR, you would have a bunch of characters on top of each other on a paper. If you just did LF, your text lines would slowly migrate to the right on the paper. CR/LF were required for proper teletype based computing. An old Star Trek game would dump «FIRING» diagonally down the page.

Carriage Return (Mac pre-OS X)

Line Feed (Linux, Mac OS X)

Читайте также:  Install docker linux centos

Carriage Return and Line Feed (Windows)

If you see ASCII code in a strange format, they are merely the number 13 and 10 in a different radix/base, usually base 8 (octal) or base 16 (hexadecimal).

The \r and \n only works in some programming languages, although it seems to be universal among programming languages that use backslash to indicate special characters.

Jeff Atwood has a blog post about this: The Great Newline Schism

The sequence CR+LF was in common use on many early computer systems that had adopted teletype machines, typically an ASR33, as a console device, because this sequence was required to position those printers at the start of a new line. On these systems, text was often routinely composed to be compatible with these printers, since the concept of device drivers hiding such hardware details from the application was not yet well developed; applications had to talk directly to the teletype machine and follow its conventions. The separation of the two functions concealed the fact that the print head could not return from the far right to the beginning of the next line in one-character time. That is why the sequence was always sent with the CR first. In fact, it was often necessary to send extra characters (extraneous CRs or NULs, which are ignored) to give the print head time to move to the left margin. Even after teletypes were replaced by computer terminals with higher baud rates, many operating systems still supported automatic sending of these fill characters, for compatibility with cheaper terminals that required multiple character times to scroll the display.

Источник

Как n и r обрабатываются по-разному в Linux и Windows?

Я думаю n двигает иглу вниз, и r перемещение стрелки в начало строки (выравнивание по левому краю)? Я не уверен, однако. Так что, если я ошибаюсь, пожалуйста, поправьте меня.

во всяком случае, мне сказали, что Windows и Linux обрабатывают newlines и carriage returns по-разному. Я хотел бы знать, как они справляются с ними по-разному и в некоторых местах, где важно помнить. Спасибо за ответ.

Количество просмотров материала

20.02.2023 8:39 3561

Распечатать страницу

3 ответа

Я думаю, что \ n перемещает иглу вниз, а \ r перемещает иглу в начало строки (выравнивание по левому краю)? Я не уверен, хотя

Это правда, более или менее, но в основном исторический курьез. Первоначально, перевод строки (LF) был использован для того чтобы выдвинуть бумагу одной линией на принтерах и стержнях печатной копии (телетайпов); возврат каретки (CR) возвратил печатающую головку в начало строки.

Это, вероятно, все еще работает на современных принтерах при использовании в «текстовом режиме», но в остальном не имеет большого значения сегодня.

во всяком случае, мне сказали, что Windows и Linux обрабатывают новые строки и каретку возвращается по-другому.

разница Просто: разработчики ОС должны были выбрать, как представить начало новой строки в тексте в компьютерных файлах. По различным историческим причинам в мире Unix/Linux в качестве маркера перевода строки был выбран один символ LF; MS-DOS выбрала CR+LF, а Windows унаследовала этот. Таким образом, разные платформы используют разные соглашения.

на практике, это становится все меньше и меньше проблем. Маркер новой строки действительно актуален только для погромов, которые обрабатывают «обычный текст», и их не так много — он в основном влияет только на исходный код программы, файлы конфигурации и некоторые простые текстовые файлы с документацией. В настоящее время большинство программ обработки этих видов файлов (Редакторы, компиляторы и т. д.) может обрабатывать оба соглашения о новой строке, поэтому это не имеет значения какой из них вы выберете.

Читайте также:  Network utility for linux

есть некоторые случаи, когда инструменты настаивают на «своем» соглашении о новой строке (например, сценарии оболочки Unix не должны использовать CR+LF), и в этом случае вы должны использовать правильный.

CR и LF

американский стандартный код для обмена информацией (ASCII) определил управляющие символы, включая возврат каретки (CR) и перевод строки (LF), которые использовались (и все еще используются) для управления положением печати на принтерах способом, аналогичным механическим пишущим машинам, которые предшествовали ранним компьютерным принтерам.

зависимость от платформы

в Windows традиционную линию-разделитель в текстовых файлах следует КЛ ЛН

In старые (до OSX) системы Apple Macintosh традиционным разделителем строк в текстовых файлах был CR

в Unix и Linux традиционным разделителем строк в текстовых файлах является LF.

\n и \r

во многих языках программирования и сценариев \n означает «новая линия». Иногда (но не всегда) это означает символ перевода строки ASCII (LF), который, как вы говорите, перемещает курсор (или позицию печати) вниз на одну строку. В принтере или на пишущей машинке, можно бумага поднялась на одну строчку.

всегда \r означает символ возврата каретки ASCII (CR), название которого на самом деле происходит от механических пишущих машинок, где был ключ возврата каретки, из-за которого ролик («каретка»), который нес бумагу, чтобы двигаться вправо, питание от пружины, насколько это будет идти. Таким образом, устанавливаем текущую позицию набора текста на левое поле.

Программирование

в некоторых языках программирования \n может означать a зависящая от платформы последовательность символов, заканчивающихся или разделяющих строки в текстовом файле. Например в Perl, print «\n» создает другую последовательность символов в Linux, чем в Windows.

в Java, лучшая практика, если вы хотите использовать собственные окончания строк для платформы выполнения, не использовать \n или \r на всех. Вы должны использовать System.getProperty(«line.separator») . Вы должны использовать \n и \r где вы хотите LF и CR независимо от платформы (например, как используется в HTTP, FTP и других интернет коммуникационный протокол.)

действовать до его закрытия в Unix

в оболочке Unix stty команда может использоваться, чтобы заставить оболочку переводить между этими различными соглашениями. Например stty -onlcr заставит оболочку впоследствии перевести все исходящие LFs в CR LF.

Linux и OSX следуют соглашениям Unix

текстовые файлы

текстовые файлы по-прежнему чрезвычайно важны и широко используются. Например, HTML и XML примеры текстовый файл. Большинство важных интернет-протоколов, таких как HTTP, следуют соглашениям о текстовых файлах и содержат спецификации для окончаний строк.

принтеры

большинств принтеры за исключением очень самого дешевого, все еще уважают CR и LF. На самом деле они являются фундаментальными для наиболее широко используемых языков описания страниц — PCL и Postscript.

короче говоря, понадобилось для принтеров, но теперь операционки делают это немного иначе. В большинстве случаев можно просто сделать CR и LF, выполнив \r\n и в большинстве случаев, это будет работать нормально.

Источник

Оцените статью
Adblock
detector