How do I remove carriage returns from text file using Powershell?
Solution 1
Set-Content
adds newlines by default. Replacing Set-Content
by Out-File
in your last attempt in your question will give you the file you want:
Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line} |
Out-File -FilePath c:\outpath\contents2.txt
Solution 2
It's not 'r (apostrophe), it's a back tick: `r. That's the key above the tab key on the US keyboard layout. :)
Solution 3
You can simply avoid all those empty lines by using Select-Object -ExpandProperty Name
:
Get-ChildItem "$SearchPath" -Recurse |
Where { !$_.PSIsContainer } |
Select-Object -ExpandProperty Name |
Out-File "$OutPath\Contents.txt" -Encoding ASCII -Width 200
... if you don't need the folder names.
user1417978
Updated on August 21, 2022Comments
-
user1417978 over 1 year
I'm outputting the contents of a directory to a txt file using the following command:
$SearchPath="c:\searchpath" $Outpath="c:\outpath" Get-ChildItem "$SearchPath" -Recurse | where {!$_.psiscontainer} | Format-Wide -Column 1' | Out-File "$OutPath\Contents.txt" -Encoding ASCII -Width 200
What I end up with when I do this is a txt file with the information I need, but it adds numerous carriage returns I don't need, making the output harder to read.
This is what it looks like:
c:\searchpath\directory name of file.txt name of another file.txt c:\searchpath\another directory name of some file.txt
That makes a txt file that requires a lot of scrolling, but the actual information isn't that much, usually a lot less than a hundred lines.
I would like for it to look like:
c:\searchpath\directory nameoffile.txt c:\searchpath\another directory another file.txt
This is what I've tried so far, not working
$configFiles=get-childitem "c:\outpath\*.txt" -rec foreach ($file in $configFiles) { (Get-Content $file.PSPath) | Foreach-Object {$_ -replace "'n", ""} | Set-Content $file.PSPath }
I've also tried 'r but both options leave the file unchanged.
Another attempt:
Select-String -Pattern "\w" -Path 'c:\outpath\contents.txt' | foreach {$_.line}' | Set-Content -Path c:\outpath\contents2.txt
When I run that string without the Set-content at the end, it appears exactly as I need it in the ISE, but as soon as I add the Set-Content at the end, it once agains carriage returns where I don't need them.
Here's something interesting, if I create a text file with a few carriage returns and a few tabs, then if I use the same -replace script I've been using, but use
t to replace the tabs, it works perfect. But
r andn do not work. It's almost as though it doesn't recognize them as escape characters. But if I add
r and `n in the txt file then run the script, it still doesn't replace anything. Doesn't seem to know what to do with it.