How to Find 5 consecutive "0" in file?
I'd probably do this in awk
, using ,
as a delimiter:
$ awk -F, '/,0,0,0,0,0/{print $1}' file
def
However, that will also catch a line like this:
mno,6,7,0,0,0,0,0.5
To avoid that, match only if the last 0
is followed by a ,
or the end of the line:
awk -F, '/,0,0,0,0,0(,|$)/{print $1}' file
grep '0,0,0,0,0' file.txt
prints the matching line: def,6,7,0,0,0,0,0,2,5
grep '0,0,0,0,0' file.txt | cut -d, -f1
prints the first field using ,
as delimiter: def
using Raku (née Perl6)
Below is an answer that tries to incorporate (and overcome) the objections mentioned by @J-L and @terdon. Also, lines with 5-or-more consecutive zeros are returned. Start first by expanding the test file:
$ cat 5or6_consec_zeros.txt
Name,X,7/27,7/28,7/29,7/30,7/31,8/1,8/2,8/3,8/4
abc,N,5,3,8,8,0,0,0,0,11
def,Y,6,7,0,0,0,0,0,2,5
ghi,N,1,3,5,2,0,0,5,3,6
jkl,N,1,3,5,2,0,0,0,0,0.5
mno,N,7.0,0,0,0,0,2,3,4,5
pqr,Y,1,3,3,0,0,0,0,0,0
stu,Y,1,3,0,0,0,0,0,0,3
vwx,Y,1,3,8,7,0,0,0,0,0
The -ne command line flag tells Raku to run the code line-by-line. The regex tries to match two tokens. In the first token it tries to match exactly 5 repeats of a ",0
" two-character sequence. In the second token the regex tries to match either a trailing comma or end-of-line $$
token (after @terdon):
[Note in Raku the |
alternation operator implements the longest-token-matching (LTM) strategy. If at some point you need to implement a Perl5-like "first-matching" strategy in Raku, you use Raku's ||
"first-matching" alternation operator].
$ raku -ne 'when / [\,0]**5 [\,|$$] / -> { .put };' 5or6_consec_zeros.txt
def,Y,6,7,0,0,0,0,0,2,5
pqr,Y,1,3,3,0,0,0,0,0,0
stu,Y,1,3,0,0,0,0,0,0,3
vwx,Y,1,3,8,7,0,0,0,0,0
To only return the first "column" of (essentially) comma-separated-values, Raku provides an explicit split()
method:
$ raku -ne 'when / [\,0]**5 [\,|$$] / -> { put .split(",")[0] };' 5or6_consec_zeros.txt
def
pqr
stu
vwx
https://raku.org/