Powershell:如何测试一行文本是否包含换行或回车? [英] Powershell: How to I test if a line of text contains line feed or carriage return?

查看:77
本文介绍了Powershell:如何测试一行文本是否包含换行或回车?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试文本文件的第一行是否以 \r 或 \n 结尾?

How do I test if the first line of a text file is terminated with \r or \n?

我尝试了与以下类似的各种演绎.我不确定导入 powershell 的字符串(文件的第一行)甚至包含不可见的字符.我也尝试过使用StreamReader方法读取行无济于事.

I tried various renditions similar to the following. I'm not sure that the string imported into powershell (first line of the file) even contains the invisible characters. I also tried using the StreamReader method to read the line to no avail.

$master = Get-Content $masterFilename | Select-Object -First 1
if ($master.Contains("\r|\n"))
    {
        write-host "you betcha, there's a carriage return or line feed"
    }

谢谢.

推荐答案

Get-Content 将您的文件转换为基于这些字符的字符串数组.当您开始测试内容时,这些字符已被删除.如果您只是在寻找换行符的存在(您的条件似乎并不关心它遇到什么),测试从 Get-Content 返回的行数就足够了.

Get-Content converts your file into a sting array based on those characters. By the time you start to test the contents those characters have been stripped out. If you are just looking for the presence of newlines (your condition does not seem to care what it encounters) testing the amount of lines returned from Get-Content would be enough.

If((Get-Content $masterFilename).Count -gt 1){"you betcha, there's a carriage return or line feed"}

我相信你看到后我会补充的.我认为您可能需要修改您的问题以使其更具体一些.

I'm sure I will add to this once you see it. I think you might need to revise your question to be a little more specific.

Get-Content 有一个 -Raw 开关,它会保留离你想去的地方更近的新行分隔符.我不确定字符串方法是否包含支持通配符.我知道它不支持正则表达式.

Get-Content has a -Raw switch which would preserve the new line delimiters which is closer to where you want to be going. I'm not sure the string method contains supports wildcards. I do know that it does not support regex.

如果您只是对一行感到好奇,那么如上所述 -Raw 将是您的起点.考虑以下以十六进制表示的文本文件.它只是单词 hello 后跟一个换行符.

If you were just curious about one line then as mentioned above -Raw would be the place to start. Consider the following text file represented in hex. It is just the word hello followed by a newline.

68 65 6c 6c 6f 0d 0a

现在我将把该文本作为一个字符串读取,并测试字符串的末尾是否有回车和换行符.请注意,我没有用反引号逃避.我正在使用正则表达式特殊字符.(无论哪种方式都行.只是需要注意的事情.)

Now I will read that text in as one string and test if the end of the string has a carriage return and line feed. Note that I am not escaping with backticks. I am using regex special characters. (It would work either way. Just something to be aware of.)

(Get-Content c:\temp\test.txt -Raw) -match "\r\n$"
True

请注意,大多数写入文件的 PowerShell cmdlet 都会留下一个尾随换行符.所以无论你有多少行,上面的代码片段对于 Set-Content 之类的东西都是正确的.

Note that most of the PowerShell cmdlets that write to file leave a trailing newline. So no matter how many lines you have the above code snippet would be true for something like Set-Content.

这篇关于Powershell:如何测试一行文本是否包含换行或回车?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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