Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

bash: question about grep

18 views
Skip to first unread message

liha...@gmail.com

unread,
Jul 21, 2008, 2:21:05 PM7/21/08
to
For the following TAB-delimited records, I want to count number of
records with column-2 == -1 (should be 2)

===== file.txt ======
AAA -1 2008-07-14
BBB -14 2008-07-15
CCC -20 2008-07-16
DDD -1 2008-07-16
===========

I tried:

grep -c -- "-1\t" file.txt

which is not working. I know I can do it with awk, like:

awk -F'\t' '$2==-1{t++}END{print t}' file.txt

But I would rather find a `grep` solution, any thought?? many thanks,

lihao

Stephane CHAZELAS

unread,
Jul 21, 2008, 2:48:37 PM7/21/08
to
2008-07-21, 11:21(-07), liha...@gmail.com:

> For the following TAB-delimited records, I want to count number of
> records with column-2 == -1 (should be 2)
>
> ===== file.txt ======
> AAA -1 2008-07-14
> BBB -14 2008-07-15
> CCC -20 2008-07-16
> DDD -1 2008-07-16
> ===========
>
> I tried:
>
> grep -c -- "-1\t" file.txt

grep -c -- $'-1\t' file.txt

$'...' is ksh93/zsh/bash specific.

>
> which is not working. I know I can do it with awk, like:
>
> awk -F'\t' '$2==-1{t++}END{print t}' file.txt
>
> But I would rather find a `grep` solution, any thought?? many thanks,

[...]

Why, the awk solution looks a lot neater to me as closer to your
requirements.

Another one:

cut -f2 < file.txt | grep -cFxe -1


--
Stéphane

liha...@gmail.com

unread,
Jul 21, 2008, 3:00:40 PM7/21/08
to
On Jul 21, 2:48 pm, Stephane CHAZELAS <stephane_chaze...@yahoo.fr>
wrote:
> 2008-07-21, 11:21(-07), lihao0...@gmail.com:

>
> > For the following TAB-delimited records, I want to count number of
> > records with column-2 == -1   (should be 2)
>
> > ===== file.txt ======
> > AAA    -1    2008-07-14
> > BBB    -14   2008-07-15
> > CCC    -20   2008-07-16
> > DDD    -1    2008-07-16
> > ===========
>
> > I tried:
>
> >   grep -c -- "-1\t" file.txt
>
> grep -c -- $'-1\t' file.txt
>
> $'...' is ksh93/zsh/bash specific.

wow, this is impressive. do you mind to explain what exactly is the
different between $'...' and '...'. I've never seen this $'..' thing
before. :-) many thanks

>
> > which is not working. I know I can do it with awk, like:
>
> >  awk -F'\t' '$2==-1{t++}END{print t}' file.txt
>
> > But I would rather find a `grep` solution, any thought?? many thanks,
>
> [...]
>
> Why, the awk solution looks a lot neater to me as closer to your
> requirements.

yes, just want to ask 'WHY' that grep line is not working...

> Another one:
>
> cut -f2 < file.txt | grep -cFxe -1

nice solution, :-)

thanks again,
lihao

> --
> Stéphane

0 new messages