如何更改 sed 认为的行分隔符 [英] How to change what sed thinks is the line delimiter

查看:31
本文介绍了如何更改 sed 认为的行分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我是 sed 的新手,我很高兴看到 sed 不认为 \r 字符是有效的行分隔符.

As I'm new with sed, I'm having the fun of seeing that sed doesn't think that the \r character is a valid line delimiter.

有谁知道如何告诉 sed 在处理多行文本时我希望它使用哪些字符作为行分隔符?

Does anyone know how to tell sed which character(s) I'd like it to use as the line delimiter when processing many lines of text?

推荐答案

(为了使下面的示例更清晰、更清晰,我将使用 od util.)

(For making the examples below clearer and less ambiguous, I'll use the od util extensively.)

例如,不可能使用标志.我敢打赌,最好的解决方案是前面的答案所引用的解决方案:使用 tr.如果您有如下文件:

It is not possible to do with a flag, for example. I bet the best solution is the one cited by the previous answers: using tr. If you have a file such as the one below:

$ od -xc slashr.txt
0000000      6261    0d63    6564    0d66                                
           a   b   c  \r   d   e   f  \r                                
0000010

tr有多种使用方式;我们想要的是为其传递两个参数 - 两个不同的字符 - 而 tr 将用第二个参数替换第一个参数.将文件内容作为 tr '\r' '\n' 的输入发送,我们得到以下结果:

There are various ways of using tr; the one we wanted is to pass two parameters for it - two different chars - and tr will replace the first parameter by the second one. Sending the file content as input for tr '\r' '\n', we got the following result:

$ tr '\r' '\n' < slashr.txt | od -xc 
0000000      6261    0a63    6564    0a66                                
           a   b   c  \n   d   e   f  \n                                
0000010

太好了!现在我们可以使用sed:

Great! Now we can use sed:

$ tr '\r' '\n' < slashr.txt | sed 's/^./#/'
#bc
#ef
$ tr '\r' '\n' < slashr.txt | sed 's/^./#/' | od -xc
0000000      6223    0a63    6523    0a66                                
           #   b   c  \n   #   e   f  \n                                
0000010

但我认为您需要使用 \r 作为行分隔符,对吗?在这种情况下,只需使用 tr '\n' '\r' 来反转转换:

But I presume you need to use \r as the line delimiter, right? In this case, just use tr '\n' '\r' to reverse the conversion:

$ tr '\r' '\n' < slashr.txt | sed 's/^./#/' | tr '\n' '\r' | od -xc
0000000      6223    0d63    6523    0d66                                
           #   b   c  \r   #   e   f  \r                                
0000010

这篇关于如何更改 sed 认为的行分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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