Need to replace \x0d\x0a
with \x2c\x0d\x0a
in a file.
I can do it relatively easy on Unix:
awk '(NR>1){gsub("\r$",",\r")}1' $file > "fixed_$file":
Need help with implementing this in PowerShell.
Thank you in advance.
Need to replace \x0d\x0a
with \x2c\x0d\x0a
in a file.
I can do it relatively easy on Unix:
awk '(NR>1){gsub("\r$",",\r")}1' $file > "fixed_$file":
Need help with implementing this in PowerShell.
Thank you in advance.
Assuming that you're running this on Windows (where \r\n
(CRLF) newlines are the default), the following command
is the equivalent of your awk
command:
Get-Content $file | ForEach-Object {
if ($_.ReadCount -eq 1) { $_ } else { $_ -replace '$', ',' }
} | Set-Content "fixed_$file"
Caveat: The character encoding of the input file is not preserved, and
Set-Content
uses a default, which you can override with -Encoding
.
In Windows PowerShell, this default is the system's "ANSI" encoding, whereas in PowerShell Core it is BOM-less UTF-8.
Get-Content $file
reads the input file line by line.
The ForEach-Object
loop passes the 1st line ($_.ReadCount -eq 1
) through as-is ($_
), and appends ,
(which is what escape sequence \x2c
in your awk
command represents) to all others ($_ -replace '$', ','
).
$_ + ','
or "$_,"
are simpler alternatives for appending a comma; the regex-based -replace
operator was used here to highlight the PowerShell feature that is similar to awk
's gsub()
.Set-Content
then writes the resulting lines to the target file, terminating each with the platform-appropriate newline sequence, which on Windows is CRLF (\r\n
).