如何在 Bash 脚本中将 DOS/Windows 换行符 (CRLF) 转换为 Unix 换行符 (LF) [英] How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script

查看:78
本文介绍了如何在 Bash 脚本中将 DOS/Windows 换行符 (CRLF) 转换为 Unix 换行符 (LF)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何以编程方式(即,不使用 vi)将 DOS/Windows 换行符转换为 Unix?

How can I programmatically (i.e., not using vi) convert DOS/Windows newlines to Unix?

dos2unixunix2dos 命令在某些系统上不可用.如何使用 sedawktr 等命令来模拟这些?

The dos2unix and unix2dos commands are not available on certain systems. How can I emulate these with commands like sed, awk, and tr?

推荐答案

可以使用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.

这篇关于如何在 Bash 脚本中将 DOS/Windows 换行符 (CRLF) 转换为 Unix 换行符 (LF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆