Windows files cannot be read after being uploaded to Linux server. It turns out that it is a line break problem

When I copied the file test.txt written in vim on Linux to Windows, all the contents were displayed in one line. When I copied the test.txt created on Windows to Linux, the Linux program ran abnormally. When you write a Linux shell script on Windows and copy it to Linux to run, problems will occur. The problem lies in the line break character ^M!

How to remove \r in Windows file in Linux

Copy the file test.txt written in vim toWhen you write a linux shell script on Windows and copy it to Linux, problems will occur. The problem lies in^M on the body!

In Unix systems, each line ends with "<换行>", that is, "\n";
In Windows, each line ends with "<换行><回 车>", that is, "\n\r".
A direct result is that when a file under Unix system is opened in Windows, all the text will become one line;
If a file in Windows is opened under Unix, there may be an extra ^M symbol at the end of each line.
Use vim to process
In vim command mode, enter %s/^M$//g
Pressing Enter will automatically delete all ^M characters in the file.
So, what does this command mean? % means to match the entire file, s means substitution, ^M should be entered using Ctrl + V Ctrl + M, $ after M means to match the content at the end of the line, and the last g means that the matched content in each line must be replaced.
Once you understand the meaning of the command, it will be easier to use it flexibly. For example, if you want to replace all Vim in a file with VIM, you can use a command like this: :%s/Vim/VIM/g.

Method 1: :%s/^M//g

In command mode: input: %s/^M//g and then press Enter to replace
Note that the input of "^M" is generated by "Ctrl+v" and "Ctrl+M" respectively.

Method 2::set fileformat=unix

Opening text files with vi
vi The name of the file to be edited
Enter in command mode
:set fileformat=unix
:w

Method 3: Using sed tool

Using sed Tool
sed 's/^M//' filename > tmp_filename

Method 4: tr -d '\r'

Since there is an extra '\r' in the carriage return character under Windows, of course, by deleting '\r', you can also achieve:
tr -d '\r'

Method 5: dos2unix command (most commonly used method)

dos2unix command:
dos2unix The name of the file to be converted
Convert files directly to Unix format
The above method can convert files edited under Windows into files that can be read under Linux.

1/5 - (1 vote)

Leave a Reply

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