Get-Content and show control characters such as `r - visualize control characters in strings

Shaun Luttin picture Shaun Luttin · Dec 1, 2014 · Viewed 10.5k times · Source

What flag can we pass to Get-Content to display control characters such as \r\n or \n?

What I am trying to do, is to determine whether the line endings of a file are in the Unix or Dos style. I have tried simply running Get-Content, which doesn't show any line ending. I have also tried using Vim with set list, which just shows the $ no matter what the line ending is.

I would like to do this with PowerShell, because that would be mighty useful.

Answer

Keith Hill picture Keith Hill · Dec 1, 2014

One way is to use Get-Content's -Encoding parameter e.g.:

Get-Content foo.txt -Encoding byte | % {"0x{0:X2}" -f $_}

If you have the PowerShell Community Extensions, you can use the Format-Hex command:

Format-Hex foo.txt

Address:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F ASCII
-------- ----------------------------------------------- ----------------
00000000 61 73 66 09 61 73 64 66 61 73 64 66 09 61 73 64 asf.asdfasdf.asd
00000010 66 61 73 0D 0A 61 73 64 66 0D 0A 61 73 09 61 73 fas..asdf..as.as

If you really want to see "\r\n" in the output than do what BaconBits suggests but you have to use the -Raw parameter e.g.:

(Get-Content foo.txt -Raw) -replace '\r','\r' -replace '\n','\n' -replace '\t','\t'

Outputs:

asf\tasdfasdf\tasdfas\r\nasdf\r\nas\tasd\r\nasdfasd\tasf\tasdf\t\r\nasdf