且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Bash 脚本中将 DOS/Windows 换行符 (CRLF) 转换为 Unix 换行符 (LF)

更新时间:2023-02-18 17:25:27

可以使用tr从DOS转换到Unix;但是,只有当 CR 仅作为 CRLF 字节对的第一个字节出现在您的文件中时,您才能安全地执行此操作.这通常是这种情况.然后你使用:

You can use tr to convert from DOS to Unix; however, you can only do this safely if CR appears in your file only as the first byte of a CRLF byte pair. This is usually the case. You then use:

tr -d ' 15' <DOS-file >UNIX-file

注意名称DOS-file与名称UNIX-file不同;如果您尝试两次使用相同的名称,则最终文件中将没有数据.

Note that the name DOS-file is different from the name UNIX-file; if you try to use the same name twice, you will end up with no data in the file.

你不能反过来做(使用标准的tr").

You can't do it the other way round (with standard 'tr').

如果您知道如何在脚本中输入回车符(control-Vcontrol-M 输入 control-M),那么:

If you know how to enter carriage return into a script (control-V, control-M to enter control-M), then:

sed 's/^M$//'     # DOS to Unix
sed 's/$/^M/'     # Unix to DOS

其中 '^M' 是 control-M 字符.您还可以使用 bash ANSI-C引用机制指定回车:

where the '^M' is the control-M character. You can also use the bash ANSI-C Quoting mechanism to specify the carriage return:

sed $'s/
$//'     # DOS to Unix
sed $'s/$/
/'     # Unix to DOS

但是,如果您必须经常这样做(粗略地说不止一次),安装转换程序(例如 dos2unixunix2dos,或者dtouutod) 并使用它们.

However, if you're going to have to do this very often (more than once, roughly speaking), it is far more sensible to install the conversion programs (e.g. dos2unix and unix2dos, or perhaps dtou and utod) and use them.

如果需要处理整个目录和子目录,可以使用zip:

If you need to process entire directories and subdirectories, you can use zip:

zip -r -ll zipfile.zip somedir/
unzip zipfile.zip

这将创建一个 zip 存档,行尾从 CRLF 更改为 CR.unzip 然后会将转换后的文件放回原处(并逐个文件询问您 - 您可以回答:全部是).感谢@vmsnomad 指出这一点.

This will create a zip archive with line endings changed from CRLF to CR. unzip will then put the converted files back in place (and ask you file by file - you can answer: Yes-to-all). Credits to @vmsnomad for pointing this out.