Nadav Peled
Nadav Peled

Reputation: 1011

shell - grep - how to get only lines that have certain amount char

good morning. I have the following lines :

1 | blah | 2 | 1993 | 86 | 0 | NA | 123 | 123
1 | blah | TheBeatles | 0 | 3058 | NA | NA | 11

And I wanna get only the lines with 7 "|" and the same first field.

So the output for these two lines will be nothing, but for these two lines :

1 | blah | 2 | 1993 | 86 | 0 | NA | 123 
1 | blah | TheBeatles | 0 | 3058 | NA | NA | 11

The output will be "error".
I'm getting the inputs from a file using the following command :

grep '.*|.*|.*|.*|.*|.*|.*|.*' < $1 | sort -nbsk1 | cut -d "|" -f1 | uniq -d |
while read line2; do
  echo error
done

But this implementation would still print error even if I have more then 7 "|".
Any suggestions ?

P.S - I can assume that there is a \n in the end of each line.

Upvotes: 1

Views: 168

Answers (4)

mark
mark

Reputation: 354

I would suggest that you use awk for this job.

BEGIN { FS = "|" }
NF == 8 && $1 == '1' { print $0}

would do the job (although the == and && could be = and & ; my awk is a bit rusty)

Upvotes: 0

Gagan
Gagan

Reputation: 11

Assuming zz.txt is:

$ cat zz.txt

1 | blah | 2 | 1993 | 86 | 0 | NA | 123 | 123
1 | blah | TheBeatles | 0 | 3058 | NA | NA | 11

$ cut  -d\| -f1-8 zz.txt

above cut will give you the output you need.

Upvotes: 1

Salah Eddine Taouririt
Salah Eddine Taouririt

Reputation: 26415

With grep

grep '^\([^|]*|[^|]*\)\{7\}$'

Upvotes: 1

devnull
devnull

Reputation: 123528

For printing lines containing only 7 |, try:

awk -F'|' 'NF == 8' filename

If you want to use bash to count the number of | in a given line, try:

line="1 | blah | 2 | 1993 | 86 | 0 | NA | 123 | 123";
count=${line//[^|]/};
echo ${#count};

Upvotes: 2

Related Questions