locked
Double quotes in cmd RRS feed

  • Question

  • Hi All,

    Hopefully this is a very straightforward question, and apologies for asking if so but despite a lot of googling I can't quite get to the bottom of it :(

    With the below code I'm simply trying to replace a string in a txt file, but as the 'Set' command already uses the = symbol, which happens also to be contained in the string I wish to replace, it doesnt execute correctly.

    I'm guessing i need to wrap the second = in quote also somehow, but can't quite figure it out. 

    @echo off
    set "replace=#user=guest"
    set "replaced=user=StoreUser1"

    set "source=C:\Users\adam\Desktop\test.txt"
    set "target=C:\Users\adam\Desktop\test1.txt"

    setlocal enableDelayedExpansion
    (
       for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %source%') do (
          set "line=%%b"
          if defined line set "line=!line:%replace%=%replaced%!"
          echo(!line!
       )
    ) > %target%
    endlocal

    Any help would be greatly appreciated!

    Adam

    Friday, October 5, 2018 11:32 AM

Answers

  • @echo off
    set filename=C:\Users\adam\Desktop\test.txt
    powershell -Command "(Get-Content %filename%)| ForEach-Object{$_ -replace '#user=guest','user=StoreUser1'} | Out-File  %filename%"
    


    \_(ツ)_/

    • Marked as answer by Adam_231 Friday, October 5, 2018 1:27 PM
    Friday, October 5, 2018 1:11 PM

All replies

  • $file = 'C:\Users\adam\Desktop\test.txt'
    (Get-Content $file)| ForEach-Object{$_ -replace '#user=guest','user=StoreUser1'} | Set-Content $file


    \_(ツ)_/


    • Edited by jrv Friday, October 5, 2018 11:49 AM
    Friday, October 5, 2018 11:44 AM
  • Hi JRV,

    Many thanks for taking the time to reply.

    I'd love to use PowerShell, but this is only a small piece of a much larger script, rewriting it all for this one function would be difficult

    I don't suppose you would know the correct approach based on batch?

    Adam 

    Friday, October 5, 2018 12:46 PM
  • @echo off
    set filename=C:\Users\adam\Desktop\test.txt
    powershell -Command "(Get-Content %filename%)| ForEach-Object{$_ -replace '#user=guest','user=StoreUser1'} | Out-File  %filename%"
    


    \_(ツ)_/

    • Marked as answer by Adam_231 Friday, October 5, 2018 1:27 PM
    Friday, October 5, 2018 1:11 PM
  • Brilliant! Many thanks
    Friday, October 5, 2018 1:27 PM