Introduction
Linux
Line breaks in is essential for formatting text output, modifying files, and ensuring cross-system compatibility.
Linux
Mainly usedLF
(line breaks,\n
) to wrap the line, andWindows
useCRLF
(carriage return + line break,\r\n
)
Detect newlines in files
Use cat -A to view newlines
cat -A
OutputLinux
style,LF \n
:
Hello World$
OutputWindows
style,CRLF \r\n
:
Hello World^M$
$
: Indicates the end of the line (LF
)^M$
: means that the file hasWindows
Line 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
:Windows
The end of the style\n
:Linux
The style ends
Line break format conversion
Convert Windows CRLF (\r\n) to Linux LF (\n)
- use
dos2unix
dos2unix
- use
sed
sed -i 's/\r$//'
- use
tr
cat | tr -d '\r' > newfile_unix.txt
Convert Linux LF (\n) to Windows CRLF (\r\n)
unix2dos
unix2dos
- use
sed
sed -i 's/$/\r/'
- use
awk
awk '{print $0 "\r"}' > newfile_windows.txt
Add line breaks to the output
Print multiple lines of text
- use
echo -e
echo -e "Line 1\nLine 2\nLine 3"
Output:
Line 1 Line 2 Line 3
- use
printf
printf "Line 1\nLine 2\n"
Insert line breaks in command
Use sed
echo "Hello World" | sed 's/ / \n/g'
Output:
Hello World
- use
awk
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' > 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
- use
sed
sed -i 's/\r$//'
- use
vim
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!