Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change specific string in a project with batch

I'm developing one application. Some path have to be changed on the whole project. The path are fixed and the files can be edited (it is in .cshtml ).

So I think I can use a batch file to change all the http://localhost.com to http://domain.com for example (I know relative and absolute path, but here I HAVE to make that.

I want to use this script in many computers, so I don't want to install an application and use that app with a script... Just run .bat and that's it...

So if you have code that can make that changes in files, it could be marvellous!

To complete my question, here it is the path of files and dir

MyApp
MyApp/Views
MyApp/Views/Index/page1.cshtml
MyApp/Views/Index/page2.cshtml
MyApp/Views/Another/page7.cshtml
...
like image 917
clement Avatar asked Jan 27 '26 14:01

clement


1 Answers

You can use GNU Win32 sed for this:

for /r "MyApp/Views" %%a in (*.cshtml) do sed -ibak "s#http://localhost\.com#http://domain.com#g" "%%~a"

The for /r loop searches all folders recursively and sed changes the URL's in all *.cshtml files. It also makes a backup copy *.bak.


Batch is much lesser safe, but if you want- here is my suggestion in batch:

@echo OFF &SETLOCAL
SET "fpath=MyApp\Views"
SET "newext=.new"

SET "fname="
for /r "%fpath%" %%a in (*.cshtml) DO SET "fname=%%~a"&CALL:process
goto:eof

:process
(FOR /f "delims=" %%b IN ('findstr /n "^" "%fname%"') DO (
    SET "line=%%b"
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET "line=!line:*:=!"
    IF "!line:http://localhost.com=!" neq "!line!" (
        SET "line=!line:http://localhost.com=http://domain.com!"
    )
    ECHO(!line!
    ENDLOCAL
))>"%fname%%newext%"
goto:eof

How it works:

  • the first for loop: read the directory of the startfolder recursively, put the file names successively in a variable and call a sub routine process for each file.
  • the second for loop: read the file line by line with the use of findstr to preserve empty lines. Replace all http://localhost.com to http://domain.com if it appears and write the lines to a new file.

Used variables:

  • %fpath% path to files to process, default MyApp\Views
  • %newext% extension for the new file, default .new

Benefits:

  • preserve empty lines with findstr
  • preserve exclamation marks by toggeling delayed expansion in the second for loop
  • preserve percent signs % in file names by use of a global variable

Issues:

  • Windows Command Shell Language (WCSL, aka 'batch') can not treat lines longer than 8191 characters, not so much for HTML content
  • well, batch is not a racing car and dependent of the amount of your content this can be an veritable overnight job

Good luck!

like image 124
Endoro Avatar answered Jan 30 '26 06:01

Endoro