2

This is my code. All I'm trying to do is copy the contents of a txt file which has php code written in, replace certain phrases in that txt file with user input and then save it in another file. I'm still a newbie with cmd. any solutions to this?

@echo off 
SETLOCAL EnableDelayedExpansion
type config.txt
set /p Build=<config.txt
@echo Achese : Please check the config.php file and input the right values
@echo "Achese : Type The Video Name Below eg: your file.mp4"
set /p video=""
@echo "Achese : Type The Video Resolution Below"
@echo "Achese : What is the video width"
set /p width=""
@echo "Achese : What is the video height"
set /p height=""
@echo "Achese : What is the duration of the video"
@echo "Achese : How many seconds is the video"
set /p seconds=""
set str=!Build!
set str=!str!
set str=%str:CMDTIMEINPUT=!seconds!%
set str=%str:CMDWIDTH=!width!%
set str=%str:CMDHEIGHT=!height!%
set str=%str:CMDFILE=!video!%
echo %str% > txt.txt
php -f goLive.php
pause

this is the file I'm trying to edit

<?php
//Instagram Credentials
define('IG_USERNAME', 'thesextrovert');
define('IG_PASS', 'calaga50');

/*
 * Settings below this line are optional!
 */

//General Settings
define('UPDATE_AUTO', FALSE); //Change to true if you want the script to automatically update itself without having to run the update.php script
define('STREAM_RECOVERY', true); //Change to false if you want to disable automatic stream recovery (May improve performance when disabled)

//OBS Settings
define('OBS_MODIFY_SETTINGS', true); //Change this to false if you want the script to only modify the stream url and key and not resolution
define('OBS_BITRATE', '4000');

define('OBS_CUSTOM_PATH', 'INSERT_PATH'); //**OPTIONAL** Specify a custom path for the script to search for an obs executable
define('OBS_EXEC_NAME', 'obs64.exe'); //Recommend you don't touch this unless you modify the custom path & know what you're doing

define('OBS_X', '396'); //You shouldn't touch this
define('OBS_Y', '704'); //You shouldn't touch this


//Web console settings
define('WEB_HOST', '127.0.0.1'); //The IP to bind the web console to
define('WEB_PORT', '80'); //The port to bind the web console to

define('ANALYTICS_OPT_OUT', false); //Change to true if you want to opt of of anonymous analytics.

//Config Metadata
define('configVersionCode', '9'); //You shouldn't touch this


    define('OUTPUT_H',0); //OUTPUT TIMER HOURS
    define('CMD_TIMER',CMDTIMEINPUT); //CMD CALL TIMER SECONDS
    define('VIDEO_WIDTH',CMDWIDTH); //THE VIDEO WIDTH
    define('VIDEO_HEIGHT',CMDHEIGHT); //THE VIDEO HEIGHT
    define('STREAM_FILE',CMDFILE'); //FILE TO STREAM

    function splitTimer(){
        $time = CMD_TIMER;
        $minutes = 0;
        $seconds = 30;
            if(is_numeric($time) && $time < 3600){
                $minutes = floor(($time / 60) % 60);
                $seconds = $time % 60;
            }
            define('OUTPUT_M',$minutes); //OUTPUT TIMER MINUTES
            define('OUTPUT_S',$seconds); //OUTPUT TIMER SECONDS
    }

    function videoDimensions($width,$height,$limitWidth,$limitHeight){
            $width = abs($width);
            $height = abs($height);
            $old_width = $width;
            $old_height = $height;
                if($width > $limitWidth && $height > $limitHeight){
                    if($width < $height) list($height,$width) = array($width,$height);
                    if( $height == 0) return $width;
                    $r = $width % $height;

                    while(($r > 0) && $old_width > $limitWidth && $old_height > $limitHeight){
                        $old_width = $width;
                        $old_height = $height;
                        $width = $height;
                        $h = $r;
                        $r = $width % $height;

                        if($width < $limitWidth || $height < $limitHeight){
                            $width = $old_width;
                            $height = $old_height;
                            break;
                        }

                    }
                    return ['width'=>$width,'height'=>$height];
                }else {
                    $loop = true;

                    while($loop){
                        $old_width = $old_width * 2;
                        $old_height = $old_height * 2;

                        $width = $old_width;
                        $height = $old_height;
                            if($old_width > $limitWidth && $old_height > $limitHeight){
                                $loop = false;
                            }

                    }
                    return ['width'=>$width,'height'=>$height];
                }
        }


    function streamTime(){
        $output_s = 0;
        $output_h = 0;
        if(IS_NUMERIC(OUTPUT_S) && OUTPUT_S < 60){
            $output_s = OUTPUT_S;
        }
        if(IS_NUMERIC(OUTPUT_M) && OUTPUT_M < 60){
            $output_h = OUTPUT_H;
        }
        define('USER_STREAM_MAX_TIME',($output_s + ($output_h * 60)));
        return USER_STREAM_MAX_TIME;
    }

    function useOBS(){
        RETURN TRUE;
    }

    function autoArchive(){
        RETURN TRUE;
    }

    function autoServiceState($object)
    {
        $profile = $object->profile_name;
        if($object->slobsPresent){
            $path = getenv("appdata") . "\slobs-client\\".$profile.".json";
        }else{
            $path = getenv('appdata') . "\obs-studio\basic\scenes\\".$profile.".json";
        }

        $default_contents = '{ "current_program_scene": "Scene", "current_scene": "Scene", "current_transition": "Cut", "groups": [], "modules": { "auto-scene-switcher": { "active": false, "interval": 300, "non_matching_scene": "", "switch_if_not_matching": false, "switches": [] }, "captions": { "enabled": false, "lang_id": 1033, "provider": "mssapi", "source": "" }, "output-timer": { "autoStartRecordTimer": false, "autoStartStreamTimer": true, "pauseRecordTimer": true, "recordTimerHours": 0, "recordTimerMinutes": 0, "recordTimerSeconds": 30, "streamTimerHours": 0, "streamTimerMinutes": 0, "streamTimerSeconds": 22 }, "scripts-tool": [] }, "name": "Untitled", "preview_locked": false, "quick_transitions": [ { "duration": 300, "hotkeys": [], "id": 1, "name": "Cut" }, { "duration": 300, "hotkeys": [], "id": 2, "name": "Fade" } ], "saved_projectors": [], "scaling_enabled": true, "scaling_level": 0, "scaling_off_x": 0, "scaling_off_y": 0, "scene_order": [ { "name": "Scene" } ], "sources": [ { "balance": 0.5, "deinterlace_field_order": 0, "deinterlace_mode": 0, "enabled": true, "flags": 0, "hotkeys": { "OBSBasic.SelectScene": [], "libobs.hide_scene_item.Media Source": [], "libobs.show_scene_item.Media Source": [] }, "id": "scene", "mixers": 0, "monitoring_type": 0, "muted": false, "name": "Scene", "prev_ver": 402653187, "private_settings": [], "push-to-mute": false, "push-to-mute-delay": 0, "push-to-talk": false, "push-to-talk-delay": 0, "settings": { "custom_size": false, "id_counter": 12, "items": [ { "align": 5, "bounds": { "x": '.OBS_X.', "y": '.OBS_Y.' }, "bounds_align": 0, "bounds_type": 2, "crop_bottom": 0, "crop_left": 0, "crop_right": 0, "crop_top": 0, "group_item_backup": false, "id": 12, "locked": false, "name": "Media Source", "pos": { "x": 0, "y": 0 }, "private_settings": [], "rot": 0, "scale": { "x": 1, "y": 1 }, "scale_filter": "disable", "visible": true } ], "local_file": "success" }, "sync": 0, "volume": 1 }, { "balance": 0.5, "deinterlace_field_order": 0, "deinterlace_mode": 0, "enabled": true, "flags": 0, "hotkeys": { "MediaSource.Restart": [], "libobs.mute": [], "libobs.push-to-mute": [], "libobs.push-to-talk": [], "libobs.unmute": [] }, "id": "ffmpeg_source", "mixers": 255, "monitoring_type": 0, "muted": false, "name": "Media Source", "prev_ver": 402653187, "private_settings": [], "push-to-mute": false, "push-to-mute-delay": 0, "push-to-talk": false, "push-to-talk-delay": 0, "settings": { "local_file": "success" }, "sync": 0, "volume": 1 } ], "transition_duration": 2, "transitions": [] }';
        $file_contents = json_decode($default_contents, true);
        $timerSeconds = OUTPUT_S;
        $timerHours = OUTPUT_H;
        $timerMinutes = OUTPUT_M;

        if (file_exists($path)) {
            $file_contents = json_decode(@file_get_contents($path), true);
        }


        $video_frame = videoDimensions(VIDEO_WIDTH,VIDEO_HEIGHT,OBS_X,OBS_Y);
        $file_contents['modules']['output-timer']['streamTimerSeconds'] = $timerSeconds;
        $file_contents['modules']['output-timer']['streamTimerHours'] = $timerHours;
        $file_contents['modules']['output-timer']['streamTimerMinutes'] = $timerMinutes;
        $file_contents['modules']['output-timer']['autoStartStreamTimer'] = true;
        $file_contents['scaling_enabled'] = true;
        $file_contents['sources'][0]['settings']['local_file'] = STREAM_FILE;
        $file_contents['sources'][1]['settings']['local_file'] = STREAM_FILE;


        @file_put_contents($path, json_encode($file_contents, JSON_PRETTY_PRINT));

        Utils::log("ACHESE : UPDATE SET");
    }

    splitTimer();

all i want to do is edit this code above which is in a txt file then write the edited code into another file.

Chase
  • 31
  • 2

2 Answers2

0
@echo off
setlocal enabledelayedexpansion
set seconds=101
set width=102
set height=103
set video=104
(for /f "tokens=* delims=" %%a in ('type config.txt ^|findstr /n "^"') do (
  set "str=%%a"
  set "str=!str:CMDTIMEINPUT=%seconds%!"
  set "str=!str:CMDWIDTH=%width%!"
  set "str=!str:CMDHEIGHT=%height%!"
  set "str=!str:CMDFILE=%video%!"
  for /f "tokens=1* delims=:" %%b in ("!str!") do echo(%%c
))>txt.txt
fc config.txt txt.txt

Batch isn't suited very well for text processing (especially some special chars like <>|&=!%^ can be problematic)

We first need to read each line (for /f ... %%a). To keep formatting and empty lines, we have to use some tricks:
type file.txt|findstr /n "^" to prepend each line with its line number, so it isn't empty anymore.

"tokens=* delims=" don't tokenize (dissect) the line and don't use any delimiters (see for /? for details)

Then we replace the search strings with the correct values (see delayed expansion for the usage of !)

When that is done, we need to write the changed line while removing the line number with another for /f ... %%b loop, again using some tricks:

"tokens=1* delims=:" to split the string into the part (token 1 = %%b) before the first : and "the rest" (* = token 2 = %%c) and echo "the rest".

echo(%%c prevents a syntax error when %%c is not defined (previously an empty line) and prints an empty line instead. (same as you did with echo=, but ( is a bit safer in some situations)

We put the whole for loop in parentheses to get the whole output to a file (>txt.txt) in a single block (instead of writing line by line) (that's much faster)

The last line just compares both files and shows the differences (to verify it worked ok)

(I replaced your whole Input code for sake of readability and quick testing; just insert your original code instead)

Note: this code will delete any exclamation marks ! from the file (due to using delayed expansion. This can be changed by more code but would be slower

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • 1
    @Chase If you feel this solution answered your question, please consider marking it as the correct answer by selecting the grey tick mark on the left side of the answer. – Gerhard Dec 14 '19 at 05:51
0

This is an easier task in PowerShell, but I will address the basic issues of the cmd script here.

Not an issue per-se, but you don't need to echo then set /p you can print to the user some output through the cmd itself

To get the file read line by line we need to use a for or 'for /f` loop.

Changing the content of that string can be done in-line but since there are so many possible illegal characters and different substitutions its just a lot easier and less code to use a function to do that.

Now, outputting your code through echo this way may still cause problems, and crash the script or not output the file correctly.

Give it a shot, if the output of the text file is fine then great, if not then you may need to go through hoops to do this in cmd

@(SETLOCAL EnableDelayedExpansion
  echo off
)

CALL :Main

( endlocal
  Exit /b
)

:Main

  echo=Achese : Please check the config.php file 
  echo= 
  set /p "video=Achese : Type The Video Name eg: your file.mp4 "
  echo="Achese : Type The Video Resolution Below"
  echo=
  set /p "width=Achese : What is the video width "
  echo=
  set /p "height=Achese : What is the video height "
  echo "Achese : What is the duration of the video"
  echo=
  set /p "seconds=Achese : How many seconds is the video "

  FOR /F %%A IN ('
    type "C:\path\to\config.txt"
  ') DO (
    CALL :Replace %%A
     )
     php -f goLive.php
GOTO :EOF

:Replace
  SET Str=%*

  set str=%str:CMDTIMEINPUT=!seconds!%
  set str=%str:CMDWIDTH=!width!%
  set str=%str:CMDHEIGHT=!height!%
  set str=%str:CMDFILE=!video!%

  echo=%str%>> "c:\path\to\txt.txt""

GOTO :EOF
Ben Personick
  • 3,074
  • 1
  • 22
  • 29