1

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.

1
  • %%~dpnxa (which is equivalent to %%~fa) returns full paths, but I think you want %%~nxa to return pure file names. To get the parent name scripts you could do this: for %%a in (*) do for %%b in ("%%~dpa.") do echo(%$string%%%~nxb/%%~nxa Commented Mar 29, 2022 at 16:36

1 Answer 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]

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

1 Comment

Thank you very much. This is exactly what I am trying to achieve. Regards to my narrative with the path, I missed making changes to the path. The output I needed remains the same. Appreciate the help

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.