如何DOS / Windows的换行(CRLF)转换为Unix换行符(\\ n)在bash脚本? [英] How to convert DOS/Windows newline (CRLF) to Unix newline (\n) in bash script?

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

问题描述

我如何编程(即不使用例如)转换成DOS / Windows的换行符Unix的?

DOS2UNIX的 unix2dos 命令在某些系统上不可用,我怎么能模拟这些用命令,像 SED / AWK / TR


解决方案

您可以使用 TR 从DOS到Unix的转换;但是,如果CR出现在你的文件只是作为一个CRLF字节对的第一个字节你只能做此安全。这通常是这样的。然后,可以使用:

  TR -d'\\ 015'< D​​OS的文件> UNIX文件

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

您不能(与标准TR)做它的其他方式轮。

如果你知道如何进入回车到一个脚本(控制-V 控制-M 进入CONTROL-M),则:

  SED的/ ^ M $ //'#DOS到unix
SED的/ $ / ^ M /'#的Unix到DOS

其中'^ M'是控制-M字符。您也可以使用庆典 ANSI -C引用机制,指定回车:

  SED $的/ \\ r $ //'#DOS到unix
SED $'S / $ / \\ r /'#的Unix到DOS

不过,如果你将不得不这样做经常(超过一次,粗略地讲),这是更为明智的安装转换程序(如的 DOS2UNIX的 和的 unix2dos ,或者 dtou utod ),并使用它们。

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

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

解决方案

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

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.

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

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

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

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.

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

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