How do I test if the first line of a text file is terminated with \r or \n?
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"
}
Thank you.
CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. LF = Line Feed ( \n , 0x0A in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line.
`r`n is CRLF, the newline sequence composed of a CARRIAGE RETURN ( U+000D ) character immediately followed by an LF, used as a newline on Windows.
Use the `n Code Method The most common technique for forcing a line break is to insert `n just before the character where you want the break to occur. Note that the ` character is the backtick, not an apostrophe.
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
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.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With