在 Unix 中删除回车

编程入门 行业动态 更新时间:2024-10-25 09:26:18
本文介绍了在 Unix 中删除回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

从 Unix 中的文件中删除所有回车符 \r 的最简单方法是什么?

What is the simplest way to remove all the carriage returns \r from a file in Unix?

推荐答案

我假设你的意思是回车 (CR, "\r", 0x0d) 在行的 ends 而不是盲目地在文件中(据我所知,您可能将它们放在字符串的中间).仅在第一行末尾使用带有 CR 的测试文件:

I'm going to assume you mean carriage returns (CR, "\r", 0x0d) at the ends of lines rather than just blindly within a file (you may have them in the middle of strings for all I know). Using this test file with a CR at the end of the first line only:

$ cat infile
hello
goodbye

$ cat infile | od -c
0000000   h   e   l   l   o  \r  \n   g   o   o   d   b   y   e  \n
0000017

dos2unix 如果它安装在您的系统上,则是可行的方法:

dos2unix is the way to go if it's installed on your system:

$ cat infile | dos2unix -U | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

如果由于某种原因 dos2unix 对您不可用,那么 sed 会做到:

If for some reason dos2unix is not available to you, then sed will do it:

$ cat infile | sed 's/\r$//' | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

如果由于某种原因 sed 对你不可用,那么 ed 会以一种复杂的方式来做:

If for some reason sed is not available to you, then ed will do it, in a complicated way:

$ echo ',s/\r\n/\n/
> w !cat
> Q' | ed infile 2>/dev/null | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

如果您的机器上没有安装任何这些工具,那么您会遇到比尝试转换文件更大的问题:-)

If you don't have any of those tools installed on your box, you've got bigger problems than trying to convert files :-)

这篇关于在 Unix 中删除回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 17:14:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1176907.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Unix

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!