Egrep how to make sure string is after 5 comma

Hello,

Need help...

using egrep how do I make sure string is after 5th comma

example:

a,b,c,d,e,f,g,h,i

Suppose i want to search letter f but want to make sure it is after 5th comma.
Is there any way to check string is after 5th comma?

Thanks !!

This will print the line if the letter "f" is in field 6 or more:

echo a,b,c,d,e,f,g,h,i | awk -F, '{ p=0; for (i=6; i<=NF; i++) { if ($i ~ /f/) p=1 } } p'
1 Like

Thanks but i want to use only egrep for this.

Not sure if this is the best way to do it, but it works:

egrep '.*?,.*?,.*?,.*?,.*?,.*f' file

Edit: This is a better way to approach it:

grep '^\([^,]*,\)\{5\}\(.*f\)' file
1 Like

Why not use awk ???
awk is a good tool for this job. Here is another version.

echo a,b,c,d,e,f,g,h,i | awk 'NR>5 && $1~/f/ {print "yes"}' RS=,
yes

This prints yes if an f is found after 5th ,

1 Like

Somehow cleaner with extended grep (egrep):

grep -E '(.*,){5,}f' infile

If you're on Solaris/Oracle OS use /usr/xpg4/bin/grep .

Why not using cut : is it home work ?

cut -d, -f6- infile

echo a,b,c,d,e,f,g,h,i | awk 'NR>5 && $1~/f/ {print "yes"}' RS=,

I guest $5~/f/ { print $0 } would print the record if the fifth column has f in it.

I am going to assume that with "after 5th comma" you mean that letter "f" should be in the 6th (comma separated) column, not in column 7 or 8. In that case I would try this:

grep -E '^([^,]*,){5}[^,]*f' file

Or should it be an exact match in column 6?

grep -E '^([^,]*,){5}f(,|$)' file

In both cases this could be done easier using awk:

awk -F, '$6~/f/' file

and

awk -F, '$6=="f"' file

respectively

--
@paresh n doshi, you cannot really use RS here because you will get into trouble if there is more than 1 line, because it would then also match the pattern in the lower columns...

OP request is: Is there any way to check string is after 5th comma?
So it could be other filed than just $6, it could be $7, $8 etc.