0

So I am looping through files within a directory and want to get the filename and as i get the filename I will want to break it down with delim because I will be getting the first portion of the name before the first underscore. Many examples use this for /f loo[ with token/delim settings but when i run this code it says for the echo of i as: !var! and then when I get ride of the "" i get The system cannot find the file !var!

I am guessing my syntax is incorrect and maybe even my approach of my script is as well. Any suggestions?

@ECHO OFF

for /r %%a in (*.pdf) do (
    echo %%~nxa
    set var=%%~nxa
    
    for /F "tokens=1-2 delims=_" %%i in ("!var!") do (
        echo %%i %%j
    )

)

PAUSE
testItAll
  • 49
  • 8
  • 1
    first, to use `!var!`, you need to `setlocal enabledelayedexpansion`, second, you don't need [delayed expansion](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected/30284028#30284028), because you can use `%%~nxa` directly instead: `...%%i in ("%%~nxa") do ...` – Stephan Sep 24 '21 at 20:13
  • @Stephan ahhh thank you, now i know. This helped and out the result, much appreciated – testItAll Sep 24 '21 at 20:18
  • @Stephan how could i go about grabbing %%i value of the delimited name and cutting off leading zeros? – testItAll Sep 24 '21 at 20:37
  • 1
    `for /f "tokens=* delims=0" %%k in ("%%i") do echo %%k` – Stephan Sep 24 '21 at 20:39
  • 1
    There is no need to assign the `FOR` variable to an environmental variable. Just use the `FOR` variable with the nested `FOR` command. `for /F "tokens=1-2 delims=_" %%i in ("%%~nxa") do` – Squashman Sep 24 '21 at 20:44

1 Answers1

0

The files can be easily found and the first two portions identified with a regex expression using PowerShell. PowerShell is available on all supported Microsoft Windows platforms. PowerShell Core, the newer versions of PowerShell, can run on Linux, Mac, and also Windows.

Get-ChildItem -File -Recurse -Filter '*.pdf' |
    ForEach-Object {
        Write-Host $_.Name
        if ($_.Name -match '^(.*)_(.*)_.*') {
            Write-Host "$($Matches[1]) $($Matches[2])"
        }
    }
lit
  • 14,456
  • 10
  • 65
  • 119