Home > Mobile >  Modify For loop to go from certain string forward and delete every line containing "," usi
Modify For loop to go from certain string forward and delete every line containing "," usi

Time:03-25

Ok so i am writing a batch file in which i delete every line containing "," after finding string: "plugins": { Is it possible to make this condition in for loop ?

now i know you can avoid quotes using ^ but i just cant make it work.

what i do right now is the following:

@echo OFF
::removePlugins
setlocal enabledelayedexpansion

    echo. 2>tempPackage.json
    SET @FOUND=0
    for /F "delims=" %%G in (./package.json) do (   
        echo %%G|find "," > nul
        if not errorlevel 1 (SET @FOUND=1)  
     
        if !@FOUND!==1(
            @echo ON
            SET @FOUND=0
            ECHO:     >> tempPackage.json
            @echo OFF
        ) 
        ECHO %%G>>tempPackage.json
    )
    move "./tempPackage.json" ".package.json"

So in this case i would only make a new line in every line that contains ",". So how does one write a for loop that only goes from this string forward and not make new line but delete it?.

The file contains something like this :

"scripts"{ random scripts},
"dependencies"{ random dependencies},
"plugins": {
      "cordova-plugin-network-information": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-whitelist": {},
      "cordova-support-google-services": {},
      "cordova.plugins.diagnostic": {},
      "cordova-plugin-ionic-webview": {
        "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27. "},
}

the expected result after runing the batch would be :

"scripts"{ still the same scripts},
"dependencies"{ still the same dependencies},
"plugins": {

}

CodePudding user response:

Keep in mind, batch can't interpret .json files and handles them as pure text. So any batch solution will highly depend on the exact format of the file. Any change in the format (a stray space might be enough) may cause trash.

That said: use a flag that changes at (each) line that starts with "plugins": and changes back when hitting the line starting with } (end of the block) and write the line dependent on the flag:

@echo OFF
::removePlugins
setlocal 

SET "@FLAG=1"
>tempPackage.json (
  for /F "delims=" %%G in (./package.json) do (  
    echo %%G|findstr /b "}" >nul && SET "@FLAG=1"
    if defined @FLAG ECHO %%G
    echo %%G|findstr /b "\"plugins\":" >nul && SET "@FLAG="
  )
)
type tempPackage.json

CodePudding user response:

This uses a regex to capture everything up to the "plugins" line.

powershell -NoLogo -NoProfile -Command ^
    Get-Content -Raw .\pi.txt ^| ^
    ForEach-Object { if ($_ -match '(?sm)(.*\"plugins\": {).*') { $Matches[1]   \"`n`n}\" ^| Out-File -FilePath '.package.json'}}
  • Related