maeq
maeq

Reputation: 1103

cmd - Open file and save it - script

I need to open a .csv file and instantly save it with the same name (overwrite it) using a .bat.

This may sound stupid but it is the easiest way that I've found to change that .csv file codification (from ANSI to UTF-8).

If I type notepad file-name.csv it opens the .csv file, but how do I save it now?

Upvotes: 2

Views: 2397

Answers (2)

MC ND
MC ND

Reputation: 70923

For a pure script solution, this is a hybrid batch/javascript solution (adapted from a previous vbs answer). Adapt as needed and save as .cmd file.

@if (@this==@isBatch) @then
@echo off

    cscript //nologo //e:jscript "%~f0" ^
            /input:"input_file.csv" ^
            /output:"output_file.csv" ^
            /from:"x-ansi" ^
            /to:"utf-8"

    exit /b

@end
var adTypeText = 2;
var adSaveCreateOverWrite = 2;

var inputFile = WScript.Arguments.Named.Item('input');
var outputFile = WScript.Arguments.Named.Item('output');

var from = WScript.Arguments.Named.Item('from');
var to = WScript.Arguments.Named.Item('to');

var inputStream  = WScript.CreateObject('adodb.stream');
    with (inputStream){
        Type = adTypeText;
        Charset = from;
        Open();
        LoadFromFile( inputFile );
    }

var outputStream = WScript.CreateObject('adodb.stream')
    with (outputStream){
        Type = adTypeText;
        Charset = to;
        Open();
        WriteText( inputStream.ReadText );
        SaveToFile( outputFile, adSaveCreateOverWrite );
    }

    inputStream.Close()
    outputStream.Close()

Upvotes: 1

user330315
user330315

Reputation:

You can use the Windows port of the Linux tool iconv which can convert text files from one encoding to another.

The gnuwin32 project has ports of all major GNU utilities, including iconv which can be downloaded as a single package from here:

Upvotes: 1

Related Questions