Skip to content
Home » Shell Script » How to Distinguish Carriage Returns CR, Line Feeds LF, and New Lines CRLF on Linux

How to Distinguish Carriage Returns CR, Line Feeds LF, and New Lines CRLF on Linux

On Linux, a new line (CRLF, n) equals to a carriage return (CR, r) plus a line feed (LF, character undefined). Therefore, if you deleted a new line n, a carriage return r was deleted as well.

  1. A Carriage Return (CR): It will reset the input cursor to the leftmost of a line of text.
  2. A Line Feed (LF): It will move down one line of text.
  3. A New Line (CRLF): It will do a CR first, then do a LF.

Sometimes, we need to add or remove n or r to files manually. So let's see the effects of using n and r first.

Echo an empty line.

[root@localhost ~]$ echo | cat -n
     1

Echo an empty line and a new line, so there're two blank lines.

[root@localhost ~]$ echo $'n' | cat -n
     1
     2

Echo a string line and a new line.

[root@localhost ~]$ echo "foo"$'n' | cat -n
     1  foo
     2

Echo a new line and a string line.

[root@localhost ~]$ echo $'n'"bar" | cat -n
     1
     2  bar

Echo an empty line and a carriage return. You can see CR is no effect.

[root@localhost ~]$ echo $'r' | cat -n
     1

Echo a string line and a carriage return. CR is no effect also.

[root@localhost ~]$ echo "foo"$'r' | cat -n
     1  foo

Echo a carriage return and a string line. Oh, you can see the effect without adding a line feed LF. "bar" overwrote 3 blank spaces in the same line.

[root@localhost ~]$ echo $'r'"bar" | cat -n
bar  1

Echo a string line and a carriage return. Since there's nothing after CR, so nothing has been overwritten in the same line.

[root@localhost ~]$ echo "foo"$'r' | cat -n
     1  foo

Echo a string line, a carriage return and a string line. You can see "bar" overwrote 3 blank spaces in the same line.

[root@localhost ~]$ echo "foo"$'r'"bar" | cat -n
bar  1  foo

A more clear example by using a CR only (No LF).

[root@localhost ~]$ echo "foo"$'r'"How to SOP" | cat -n
How to SOP

You can see "How to SOP" overwrote all original output "     1  foo" in the same line and go further. So we have a conclusion: A line feed is the difference between a new line and a carriage return. Which means that if you add CR only, CR forces the cursor to the leftmost position in the same line and continue to print the output by overwriting.

Normally, a file has a CR at the end of the file. But sometimes, you might see files with no CR ended. You may refer to this post for more details:

Leave a Reply

Your email address will not be published. Required fields are marked *