배치파일 ini 읽기 및 수정

반응형

배치파일 ini 읽기 및 수정

ini.cmd, test.cmd, test.ini 을 가각 만들어서 테스트 해보세요.

ini /s {구분} /i {항목} /v {값} {ini파일} 이런식으로 입력

 

test.ini 파일의 구조가 아래와 같다고 가정할때

[Options]
sn=0
ds=0

사용법) ini /s Options /i ds /v 5 test.ini

test.cmd를 실행해보면 알겠지만 test.ini파일의 Options항목의 ds=0 값이

입력하는데로 값이 변한다는 것을 알수 있습니다.

 

 

ini.cmd

@if (@a==@b) @end /* -- batch / JScript hybrid line to begin JScript comment

:: --------------------
:: ini.cmd
:: ini.cmd /? 사용법
:: --------------------

@echo off
setlocal enabledelayedexpansion

goto begin

:: jeb의 색상 코드 -- https://stackoverflow.com/a/5344911/1683264
:c
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
exit /b
:: but it doesn't handle slashes.  :(
:s
<NUL set /p "=/"&exit /b

:usage
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do set "DEL=%%a"
<nul > X set /p ".=."

echo 사용법:
call :c 07 "   쿼리:"
call :c 0F " %~nx0 "&call :s&call :c 0F "i 항목 ["&call :s&call :c 0F "s 구분] ini파일"&echo;
call :c 07 "   생성 또는 수정:"
call :c 0F " %~nx0 "&call :s&call :c 0F "i 항목 "&call :s&call :c 0F "v 값 ["&call :s&call :c 0F "s section] ini파일"&echo;
call :c 07 "   삭제:"
call :c 0F " %~nx0 "&call :s&call :c 0F "d 항목 ["&call :s&call :c 0F "s 구분] ini파일"&echo;
echo;
echo 예를 들어 다음 ini 파일을 가져옴:
echo;
echo    [Config]
echo    password=1234
echo    usertries=0
echo    allowterminate=0
echo;
echo "password" 값을 읽으려면:
call :c 0F "   %~nx0 "&call :s&call :c 0F "s Config "&call :s&call :c 0F "i password ini파일"&echo;
echo;
echo "usertries" 값을 5로 수정하려면:
call :c 0F "   %~nx0 "&call :s&call :c 0F "s Config "&call :s&call :c 0F "i usertries "&call :s&call :c 0F "v 5 ini파일"&echo;
echo;
echo 현재 날짜 및 시간 값으로 "timestamp" 키를 추가하려면:
call :c 0F "   %~nx0 "&call :s&call :c 0F "s Config "&call :s&call :c 0F "i timestamp "&call :s&call :c 0F "v ""%DEL%%%%%date%%%% %%%%time%%%%""%DEL% ini파일"&echo;
echo;
echo "allowterminate" 키를 삭제하려면:
call :c 0F "   %~nx0 "&call :s&call :c 0F "s Config "&call :s&call :c 0F "d allowterminate ini파일"&echo;
echo;
call :c 07 "위의 예에서, "&call :s
call :c 0F "s Config "
echo 선택 사항이지만 ini 파일에 여러 섹션에 유사한 
echo 항목이 포함된 특정 항목을 선택할 수 있습니다.
del X
goto :EOF

:begin
if "%~1"=="" goto usage
for %%I in (항목 값 섹션을 찾았습니다.) do set %%I=
for %%I in (%*) do (
    if defined next (
        if !next!==/i set "item=%%~I"
        if !next!==/v (
            set modify=true
            set "value=%%~I"
        )
        if !next!==/d (
            set "item=%%~I"
            set modify=true
            set delete=true
        )
        if !next!==/s set "section=%%~I"
        set next=
    ) else (
        for %%x in (/i /v /s /d) do if "%%~I"=="%%x" set "next=%%~I"
        if not defined next (
            set "arg=%%~I"
            if "!arg:~0,1!"=="/" (
                1>&2 echo 오류: 인식할 수 없는 옵션 "%%~I"
                1>&2 echo;
                1>&2 call :usage
                exit /b 1
            ) else set "inifile=%%~I"
        )
    )
)
for %%I in (item inifile) do if not defined %%I goto usage
if not exist "%inifile%" (
    1>&2 echo 오류: %inifile% 찾을 수 없습니다.
    exit /b 1
)

cscript /nologo /e:jscript "%~f0" "%inifile%" "!section!" "!item!" "!value!" "%modify%" "%delete%"

exit /b %ERRORLEVEL%

:: Begin JScript portion */
var inifile = WSH.Arguments(0),
section = WSH.Arguments(1),
item = WSH.Arguments(2),
value = WSH.Arguments(3),
modify = WSH.Arguments(4),
del = WSH.Arguments(5),
fso = new ActiveXObject("Scripting.FileSystemObject"),
stream = fso.OpenTextFile(inifile, 1),

// (stream.ReadAll() will not preserve blank lines.)
data = [];
while (!stream.atEndOfStream) { data.push(stream.ReadLine()); }
stream.Close();

// trims whitespace from edges
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/,'') }

// trim + toLowerCase
String.prototype.unify = function() { return this.trim().toLowerCase(); };

// unquotes each side of "var"="value"
String.prototype.splitEx = function(x) {
    for (var i=0, ret = this.split(x) || []; i<ret.length; i++) {
        ret[i] = ret[i].replace(/^['"](.*)['"]$/, function(m,$1){return $1});
    };
    return ret;
}

// 비어 있지 않은 마지막 요소 바로 뒤에 새 요소를 배열에 연결합니다. 첫 번째 인수가 숫자인 경우 해당 위치에서 시작하여 마지막까지 읽어드립니다.
Array.prototype.cram = function() {
    for (var args=[], i=0; i<arguments.length; i++) { args.push(arguments[i]); }
    var i = (typeof args[0] == "number" && Math.floor(args[0]) == args[0]) ? args.shift() : this.length;
    while (i>0 && !this[--i].length) {};
    for (var j=0; j<args.length; j++) this.splice(++i, 0, args[j]);
}

function saveAndQuit() {
    while (data && !data[data.length - 1].length) data.pop();
    var stream = fso.OpenTextFile(inifile, 2, true);
    stream.Write(data.join('\r\n') + '\r\n');
    stream.Close();
    WSH.Quit(0);
}

function fatal(err) {
    WSH.StdErr.WriteLine(err);
    WSH.Quit(1);
}

if (section && !/^\[.+\]$/.test(section)) section = '[' + section + ']';

if (modify) {
    if (section) {
        for (var i=0; i<data.length; i++) {
            if (data[i].unify() == section.unify()) {
                for (var j=i + 1; j<data.length; j++) {
                    if (/^\s*\[.+\]\s*$/.test(data[j])) break;
                    var keyval = data[j].splitEx('=');
                    if (keyval.length < 2) continue;
                    var key = keyval.shift(), val = keyval.join('=');
                    if (key.unify() == item.unify()) {
                        if (del) data.splice(j, 1);
                        else {
                            data[j] = item + '=' + value;
                            WSH.Echo(value.trim());
                        }
                        saveAndQuit();
                    }
                }
                if (del) fatal(item + ' not found in ' + section + ' in ' + inifile);
                data.cram(j ,item + '=' + value);
                WSH.Echo(value.trim());
                saveAndQuit();
            }
        }
        if (del) fatal(section + ' not found in ' + inifile);
        data.cram('\r\n' + section, item + '=' + value);
        WSH.Echo(value.trim());
        saveAndQuit();
    }
    else { // if (!section)
        for (var i=0; i<data.length; i++) {
            var keyval = data[i].splitEx('=');
            if (keyval.length < 2) continue;
            var key = keyval.shift(), val = keyval.join('=');
            if (key.unify() == item.unify()) {
                if (del) data.splice(i, 1);
                else {
                    data[i] = item + '=' + value;
                    WSH.Echo(value.trim());
                }
                saveAndQuit();
            }
        }
        if (del) fatal(item + ' not found in ' + inifile);
        data.cram(item + '=' + value);
        WSH.Echo(value.trim());
        saveAndQuit();
    }
}
else if (section) { // and if (!modify)
    for (var i=0; i<data.length; i++) {
        if (data[i].unify() == section.unify()) {
            for (var j=i + 1; j<data.length; j++) {
                if (/^\s*\[.+\]\s*$/.test(data[j])) fatal(item + ' not found in ' + section + ' in ' + inifile);
                var keyval = data[j].splitEx('=');
                if (keyval.length < 2) continue;
                var key = keyval.shift(), val = keyval.join('=');
                if (key.unify() == item.unify()) {
                    WSH.Echo(val.trim());
                    WSH.Quit(0);
                }
            }
        }
    }
    fatal(section + ' not found in ' + inifile);
}
else { // if (item) and nothing else
    for (var i=0; i<data.length; i++) {
        var keyval = data[i].splitEx('=');
        if (keyval.length < 2) continue;
        var key = keyval.shift(), val = keyval.join('=');
        if (key.unify() == item.unify()) {
            WSH.Echo(val.trim());
            WSH.Quit(0);
        }
    }
    fatal(item + ' not found in ' + inifile);
}

 

test.cmd

@echo off
:main
cls
for /f "eol=[ delims=" %%a in (test.ini) do call set %%a
echo.&echo   ini파일 수정 테스트&echo.&echo   [Option] ds값 수정
echo.&echo   [Options]
echo   sn=0
echo   ds=%ds%
echo.&echo   test.ini ds값 수정 0과 1중 선택 :
choice /c 01 >nul
if %errorlevel%==1 (set i=0) else (set i=1)
ini /s Options /i ds /v %i% test.ini&call test.cmd

 

test.ini

[Options]
sn=0
ds=0

 

출처: 바로가기

 

다운로드:

ini 수정.zip
0.00MB

 

반응형

댓글

Designed by JB FACTORY