Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo "string" > file in Windows PowerShell appends non-printable character to the file

In Windows PowerShell:

echo "string" > file.txt

In Cygwin:

$ cat file.txt
:::s t r i n g

$ dos2unix file.txt
dos2unix: Skipping binary file file.txt

I want a simple "string" in the file. How do I do it? I.e., when I say cat file.txt I need only "string" as output. I am echoing from Windows PowerShell and that cannot be changed.

like image 863
Girish Vijay Avatar asked Nov 17 '11 08:11

Girish Vijay


People also ask

How do I pipe a PowerShell output to a text file?

To send a PowerShell command's output to the Out-File cmdlet, use the pipeline. Alternatively, you can store data in a variable and use the InputObject parameter to pass data to the Out-File cmdlet. Out-File saves data to a file but it does not produce any output objects to the pipeline.

How do I set encoding in PowerShell?

PowerShell uses a Unicode character set by default. However, several cmdlets have an Encoding parameter that can specify encoding for a different character set. This parameter allows you to choose the specific the character encoding you need for interoperability with other systems and applications.

How do I print the contents of a file in PowerShell?

Once you have saved the script, go to the output pane and run the script, as shown in the image below. Note, the PowerShell cmdlet for print is “Out-Printer“. The “Out-Printer” cmdlet of the PowerShell will only send data to your printer. Now, we will move towards printing a file using this “cmdlet“.

How do I write a PowerShell script to a file?

You can also use PowerShell to write to file by appending to an existing text file with Add-Content Cmdlet. To append “This will be appended beneath the second line” to our existing file, first-file. txt, enter this command and press enter.


1 Answers

Try echo "string" | out-file -encoding ASCII file.txt to get a simple ASCII-encoded txt file.

Comparison of the files produced:

echo "string" | out-file -encoding ASCII file.txt

will produce a file with the following contents:

73 74 72 69 6E 67 0D 0A (string..)

however

echo "string" > file.txt

will produce a file with the following contents:

FF FE 73 00 74 00 72 00 69 00 6E 00 67 00 0D 00 0A 00 (ÿþs.t.r.i.n.g.....)

(Byte order mark FF FE indicates the file is UTF-16 (LE). The signature for UTF-16 (LE) = 2 bytes: 0xFF 0xFE followed by 2 byte pairs. xx 00 xx 00 xx 00 for normal 0-127 ASCII chars

like image 172
jon Z Avatar answered Sep 21 '22 23:09

jon Z