'Replace Backslash with Forwardslash in Windows batch script
I am writing a simple batch script to get the filenames in a folder and write the output to a file. At the same time, I am appending a string to the file.
@echo off
set $string=!source ./
set "loc=C:\path\to\dir\files\scripts\"
pushd %loc%
(for %%a in (*) do (
echo %$string%%%~dpnxa))>output.txt
popd
output.txt:
!source ./C:\path\to\dir\files\scripts\abc.txt
!source ./C:\path\to\dir\files\scripts\xyz.txt
I am having a hard time replacing backslash \ with forward-slash / in the output and also removing this part C:\path\to\dir\files\ from the path.
In the end, I am trying to achieve something like this written to a file:
final_output.txt:
!source ./scripts/abc.txt
!source ./scripts/xyz.txt
Any help will be great.
Solution 1:[1]
@ECHO Off
SETLOCAL
set "$string=!source ./"
set "loc=U:\path\to\dir\files\scripts\"
pushd %loc%
FOR %%a IN ("%loc%.") DO SET "locparent=%%~dpa"
(for %%a in (*) do (
SET "line=%%~dpnxa"
CALL SET "line=%$string%%%line:%locparent%=%%"
CALL ECHO %%line:\=/%%))>output.txt
popd
GOTO :EOF
[I used drive u: for testing]
Yo can't substring a metavariable (%%a in this case) - you need to transfer to a uservariable.
Having established line, use call set to execute the command SET "line=valueof$string%line:valueofloc=%", which replaces the unrequired string already in line by nothing.
Then use call echo to execute ECHO %line:\=/%, replacing any remaining \ with /.
Your narrative states you wish to remove C:\path\to\dir\files\scripts from the output, but your example output includes scripts.
[adjusted include the leafname]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
