bash 转换行尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16768776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:46:17  来源:igfitidea点击:

Convert line endings

bashshellsedcommand-linedos2unix

提问by Steven Penny

I have been using d2uto convert line endings. After installing Puppy Linux I noticed that it does not come with d2u, but dos2unix. Then I noticed that Ubuntu is missing both by default.

我一直在d2u用来转换行尾。安装 Puppy Linux 后,我注意到它没有附带d2u,而是dos2unix. 然后我注意到默认情况下 Ubuntu 两者都没有。

What is another way to convert line endings?

转换行尾的另一种方法是什么?

回答by jaypal singh

Some options:

一些选项:

Using tr

使用 tr

tr -d '' < windows.txt > unix.txt

OR

或者

tr -d '\r' < windows.txt > unix.txt 

Using perl

使用 perl

perl -p -e 's/\r$//' < windows.txt > unix.txt

Using sed

使用 sed

sed 's/^M$//' windows.txt > unix.txt

OR

或者

sed 's/\r$//' windows.txt > unix.txt

To obtain ^M, you have to type CTRL-Vand then CTRL-M.

要获得^M,您必须输入CTRL-V然后CTRL-M

回答by Steven Penny

Doing this with POSIX is tricky:

用 POSIX 做到这一点很棘手:

  • POSIX Seddoes not support \ror \15. Even if it did, the in place option -iis not POSIX

  • POSIX Awkdoes support \rand \15, however the -i inplaceoption is not POSIX

  • d2uand dos2unixare not POSIX utilities, but exis

  • POSIX exdoes not support \r, \15, \nor \12

  • POSIX Sed不支持\r\15。即使是这样,就地选项-i也不是 POSIX

  • POSIX Awk确实支持\rand \15,但是该-i inplace选项不是 POSIX

  • d2udos2unix不是POSIX 实用程序,但ex

  • POSIX ex不支持\r, \15,\n\12

To remove carriage returns:

删除回车:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file

To add carriage returns:

添加回车:

awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file