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

查看:83
本文介绍了如何在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?

dos2unix unix2dos 命令在某些系统上不可用.我该如何使用 sed awk tr 等命令来模拟这些命令?

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 '\015' <DOS-file >UNIX-file

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

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-V control-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'是控制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/\r$//'     # DOS to Unix
sed $'s/$/\r/'     # Unix to DOS

但是,如果您不得不经常执行此操作(粗略地说,不止一次),则安装转换程序要明智得多(例如 unix2dos ,或者 dtou utod )并使用它们.

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天全站免登陆