0

I have a test.csv file which has data something like this.

"a","usa","24-Nov-2011","100.98","Extra1","Extra2"

"B","zim","23-Nov-2011","123","Extra22"

"C","can","23-Nov-2011","123"

I want to fetch the maximum number of columns in this file (i,e 6 in this case) and then store this in a variable.

Like

Variable=6

I'm aware that this can be acheived in scripting as I have some basic knowledge about scripting. But I have zero programming knowledge in .BAT. Please help me regarding this

ramaswamy
  • 121
  • 1
  • 2
  • 8
  • I suppose you should read/google for some basics: How to read a file, how to count the number of commas in a line, ... – jeb Feb 16 '15 at 11:51

3 Answers3

1
@echo off
setlocal EnableDelayedExpansion

set variable=0
for /F "delims=" %%a in (test.csv) do (
   set count=0
   for %%b in (%%a) do set /A count=+1
   if !count! gtr !variable! set variable=!count!
)
echo Variable=%variable%

This solution use the fact that strings enclosed in quotes in a FOR set are treated as individual items, so count they is very easy. For this reason, this method fail if there are wild-card characters ("*" or "?") in the lines.

Aacini
  • 65,180
  • 12
  • 72
  • 108
0

If comma is your delimiter, maybe you could try to count the number of commas in every line and remember the biggest one (and increase it by one). (I assume, that commas are not in the strings)

count instances of a character in file per line : https://stackoverflow.com/a/7988661/2282321

edit:

I came up with following solution, please try it (assuming input file name with data to be 'a.txt'):

@echo off
set biggest_len=0
for /f "tokens=*" %%a in (a.txt) do call :processline %%a
echo %biggest_len%
goto :eof

:processline
set len=0
for %%b in (%*) do set /A len+=1
if %len% gtr %biggest_len% set /A biggest_len=len
goto :eof

:eof

sources I used to create solution:

Batch Script - Count instances of a character in a file

If greater than batch files

batch script - read line by line

Community
  • 1
  • 1
0
@ECHO OFF
SETLOCAL
SET /a maxcols=0
SET /a mincols=999999
FOR /f "delims=" %%a IN (q28540735.txt) DO SET /a total=0&CALL :count %%a
ECHO maximum columns=%maxcols%
ECHO minimum columns=%mincols%
GOTO :EOF

:count
SET "$1=%~1"
IF DEFINED $1 SET /a total+=1&shift&GOTO count
IF %total% gtr %maxcols% SET /a maxcols=total
IF %total% lss %mincols% SET /a mincols=total
GOTO :EOF 

I used a file named q28540735.txt containing your data for my testing.

Each line is presented to the subroutine count as comma-separated parameters, so if you set the total found to zero before each call, then it's a simple matter of counting the parameters. If the parameter presented is enclosed in quotes, then any commas and spaces within the quotes are processed as being part of the token, not separators in their own right.

Magoo
  • 77,302
  • 8
  • 62
  • 84