Linux text file and WIN text file format conversion command

  • 2020-05-17 07:30:57
  • OfStack

Linux text file and WIN text file format conversion command

Preface:

Sometimes the script files edited under WIN cannot be normally executed when uploaded to LINUX server, which was initially mistaken for the configuration problem of LINUX. Later, it was found that it was caused by the difference in the newline symbol between WIN and LINUX when the files were stored. The newline character used in DOS is ^M$, which we call CR and LF. In Linux, there is only the newline character LF ($).

The format conversion can be done with the following commands: $dos2unix,$unix2dos. However, these two commands do not exist in the UBUNTU distribution and are available through:


$sudo apt-get install tofrodos

Command to install. After that, use the format shown below again.


[root@linux ~]# dos2unix [-kn] file [newfile]

[root@linux ~]# unix2dos [-kn] file [newfile]

Parameters:

-k: retain the original mtime time format of the file (do not update the last time the content of the file was modified)

-n: keep the old file and output the converted content to the new file, such as: dos2unix-n old new

Example:

Example 1: update the provided hosts file format to dos format.


[root@linux ~]# unix2dos -k hosts

unix2dos: converting file hosts to DOS format ...

The time of the hosts file will not change at this point, but the content will mainly change the newline character to CRLF of DOS.

Example 2: rename hosts, which has been changed to DOS in example 1, to hosts.dos, and convert Linux

Format to hosts linux


[root@linux ~]# mv hosts hosts.dos

[root@linux ~]# dos2unix -k -n hosts.dos hosts.linux

dos2unix: converting file hosts.dos to file hosts.linux in UNIX format ...

[root@linux ~]# ll

-rw-r--r-- 1 root root    288 Aug 1 13:30 hosts.dos

-rw------- 1 root root   279 Aug 1 13:30 hosts.linux

Because of the CR characters in DOS format, the file is larger.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: