0

I have a small problem with a .bat file that I have to build to manipulate a specific .csv. I want the .bat to read the line of the file, and then check for the first three letters of that line. At the end there should be n-files where file xxx.csv contains the lines of the input.csv with xxx as the first three letters of line.

First things first, I don't even know if it is possible to do it this job in a batch-file, because the file has >85000 lines and may even get much bigger. So if it is impossible you can directly tell me that.

for /f "delims=" %%a in (input.CSV) DO (
echo %%~a:~0,3
pause
)

I want to "output" the first three letters of %%a.

It would be great if you could help me.

Phil

Phil
  • 11
  • 2
    String substitutions can be done only with environment variables, not with loop variables. Open a [command prompt](https://www.howtogeek.com/235101/), run `set /?` and read the output help very carefully from top of first page to bottom of last page, especially the sections about string substitutions and when and how to use [delayed expansion](https://ss64.com/nt/delayedexpansion.html) explained on an __IF__ and a __FOR__ example. See also: [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/) – Mofi Apr 02 '20 at 11:48
  • I recommend to run in command prompt window also `for /?` and read the help for this command from top of first page to bottom of last page very carefully. It could be depending on unknown contents of processed CSV file that using `for /F` with appropriate `eol=`, `tokens=` and `delims=` options is enough to get assigned to the loop variable the string you want to use further. See also [this long answer](https://stackoverflow.com/a/60686543/3074564) which could be very helpful for you as beginner on writing a Windows batch file. – Mofi Apr 02 '20 at 11:54
  • If you're manipulating csv, you should use powershell. Bat can do it but it's not right for the job and 10 times harder. Also you question is kind of confusing. Any way you can clarify? – shadow2020 Apr 02 '20 at 18:23

1 Answers1

0

Substring substitution only works with environment variables (%var%), but not with metavariables (%%a) (as Mofi already commented). And because you are setting and using a variable within the same command block, you need delayed expansion:

setlocal enabledelayedexpansion
for /f "delims=" %%a in (input.CSV) DO (
  set "var=%%~a"
  echo !var:~0,3!
  pause
)

(there are methods without delayed expansion, but they make use of call, which slows things down)

Stephan
  • 53,940
  • 10
  • 58
  • 91