user3676305
user3676305

Reputation: 65

Windows command line - filter lines with non-zero values

I have a file.data whose content is as below:

140919071513,10,0,1,0,0
140919071513,11,0,1,0,0
140919071513,12,67,1,0,0
140919071513,13,89,1,0,0
140919071513,14,0,1,0,0
140919071513,15,32,1,0,0
140919071513,16,0,1,0,0
140919071513,17,0,1,0,0
140919071513,18,78,1,0,0
140919071513,19,0,1,0,0
140919071513,20,34,1,0,0

I need to run a one-line command in Windows-DOS to get the below output:

(non-zero values in 3rd column)

140919071513,12,67,1,0,0
140919071513,13,89,1,0,0
140919071513,15,32,1,0,0
140919071513,18,78,1,0,0
140919071513,20,34,1,0,0

I used this command to try to get something, but couldn't get the desired result.

for /f "tokens=* delims=," %i in file.data do echo %i

Thanks

Upvotes: 0

Views: 72

Answers (3)

MC ND
MC ND

Reputation: 70933

findstr /v /r /c:"^[^,]*,[^,]*,0," file.data

This will list all the lines that does not match (/v) the regular expression (/r) : from the start of the line (^) any sequence of zero or more characters that does not contain a comma ([^,]*), followed by a comma, any sequence of zero or more characters that does not contain a comma, a comma, a zero and a comma.

Upvotes: 2

Carsten Massmann
Carsten Massmann

Reputation: 28196

In cmd.exe you can do the following:

for /f "tokens=1-3,* delims=," %i in (tst.txt) do @if %k GTR 0 echo %i,%j,%k,%l 

Almost, what you tried, but a few changes:

... do @if ..// The @ will disable echo of the command itself ...
tokens=1-3,* // the first three tokens will be translated into variables
delims=,     // %i, %j and %k. The rest of each line ends up in %l

%k GTR 0     // GTR="greater", is a comparison of the third column against 0

This will get you

140919071513,12,67,1,0,0
140919071513,13,89,1,0,0
140919071513,15,32,1,0,0
140919071513,18,78,1,0,0
140919071513,20,34,1,0,0

Upvotes: 2

Ocaso Protal
Ocaso Protal

Reputation: 20247

Just for the case that you have Powershell at hand:

Import-Csv .\file.data -Header "A","B","C","D","E","F"|where {$_.C -ne 0}|foreach-object {Write-host("$($_.A),$($_.B),$($_.C),$($_.D),$($_.E),$($_.F)")}

The last part with the "foreach-object {Write-Host..." might be optimized, but it works in this case.

Upvotes: 2

Related Questions