1

Working on a batch script that will modify package.json file.

Basically, I need to replace the "test" portion of every json file.

This is a sample snippet:

  "scripts": {
    "test": "any text can go here"
  },

What I want to do is replace the entire "test" line with:

"test": "jest --coverage"

I have only come up with a script that replaces a string (without spaces):

SETLOCAL ENABLEDELAYEDEXPANSION

for /f "delims=" %%a in (temp.txt) do (
    SET s=%%a
    SET s=!s:test=newText!
    echo !s!>>yourtempfilename.txt
)
pause

Can anyone help me modify this so that: - it can accommodate a string with spaces - it can replace the entire line with "test" considering "any text can go here" value is always different

Please note though that I cannot use any other programs/commands such as sed or fnr.bat or something.

3
  • For editing files, do not choose cmd.exe commands, use powershell.exe with its ConvertFrom-Json and ConvertTo-Json functionality instead. Commented Dec 10, 2019 at 10:42
  • As Compo already said, batch (cmd.exe) is terrible for manipulating text files. You could use JREPL.BAT to easily and reliably accomplish your task - jrepl "test" "replacement text" /l /b /e /f "temp.txt" /o - Commented Dec 10, 2019 at 22:39
  • @dbenham: OP doesn't want to replace test, but the unknown string thereafter. (no doubt, jrepl can do that too though) Commented Dec 11, 2019 at 8:11

1 Answer 1

2

As Compo already commented, batch isn't the right tool for the job, but when you can't use anything other (like PowerShell):

@echo off
setlocal disabledelayedexpansion
set "newtext=some other text here"
(for /f "tokens=1* delims=]" %%a in ('find /n /v "" temp.txt') do (
  echo %%b|findstr /rc:"\ *\"test\":\ \".*\"" >nul && (
    for /f "delims=:" %%c in ("%%b") do echo %%c: "%newtext%"
    ) || echo/%%b
))>yourtempfilename.txt 2>nul

It keeps formatting and empty lines but has some problems with certain poison characters (that's why 2>nul; the output is ok though)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.