SoFunction
Updated on 2025-04-14

Detailed explanation of how to use Linux line breaks

Introduction

LinuxLine breaks in  is essential for formatting text output, modifying files, and ensuring cross-system compatibility.

LinuxMainly usedLF(line breaks,\n) to wrap the line, andWindowsuseCRLF(carriage return + line break,\r\n

Detect newlines in files

Use cat -A to view newlines

cat -A 

OutputLinuxstyle,LF \n

Hello World$

OutputWindowsstyle,CRLF \r\n:

Hello World^M$
  • $: Indicates the end of the line (LF)

  • ^M$: means that the file hasWindowsLine breaks (\r\n)

Check characters with od -c

od -c 

Output:Linux \n

0000000   H   e   l   l   o       W   o   r   l   d  \n

Output:Windows \r\n

0000000   H   e   l   l   o       W   o   r   l   d  \r  \n
  • \r \n: WindowsThe end of the style

  • \n: LinuxThe style ends

Line break format conversion

Convert Windows CRLF (\r\n) to Linux LF (\n)

  • usedos2unix
dos2unix 
  • usesed
sed -i 's/\r$//' 
  • usetr
cat  | tr -d '\r' > newfile_unix.txt

Convert Linux LF (\n) to Windows CRLF (\r\n)

  • unix2dos
unix2dos 
  • usesed
sed -i 's/$/\r/' 
  • useawk
awk '{print $0 "\r"}'  > newfile_windows.txt

Add line breaks to the output

Print multiple lines of text

  • useecho -e
echo -e "Line 1\nLine 2\nLine 3"

Output:

Line 1
Line 2
Line 3
  • useprintf
printf "Line 1\nLine 2\n"

Insert line breaks in command

Use sed

echo "Hello World" | sed 's/ / \n/g'

Output:

Hello
World
  • useawk
echo "Hello World" | awk '{print $1 "\n" $2}'

Handle line breaks in shell scripts

Loop through lines in a file

#!/bin/bash
while IFS= read -r line; do
    echo "Processing: $line"
done < 

Remove empty lines from file

sed -i '/^$/d' 

or

awk 'NF'  &gt; clean_file.txt

Calculate newlines in a file

grep -c '^' 

or

wc -l 

Other usages

Add text with new lines

echo "New Entry" >> 

Append to text without adding new lines

echo -n "New Entry" >> 

Check if the file ends with a new line

tail -c1  | od -c
  • If the output displays\n, means there is a line break at the end of the file.

  • If there is no output, the file lacks trailing newlines.

Using multi-line strings

Assigning multi-line strings to variables

mytext="Line 1
Line 2
Line 3"

echo "$mytext"

Read multiple lines of input using cat

cat <<EOF > 
This is line 1.
This is line 2.
EOF

Processing Windows-formatted files in Linux

Fix ^M characters in the file

  • usesed
sed -i 's/\r$//' 
  • usevim
vim 

:set fileformat=unix
:wq

The above is a detailed explanation of how to use Linux line breaks. For more information on the use of Linux line breaks, please pay attention to my other related articles!