Ryuksaple
Ryuksaple

Reputation: 23

How do I use basic grep commands in Unix?

I need to display all the lines using the grep command that contain 2-6 'x's

Also need to know how to display all lines with 3 consecutive 'x's

I have tried grep x{2,6} example.txt but I keep getting an error saying that x6 is not found in the directory. My example file contains 7 lines increasing in the amount of 'x's by one in each line.

Upvotes: 0

Views: 778

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754090

The Bash shell uses Brace Expansion to expand:

grep x{2,6} example.txt

into:

grep x2 x6 example.txt

Unless you have a file called x6 in your directory, you will get an error from grep telling you it can't open it.

  • Rule 1: enclose regular expressions to grep inside quotes — single quotes whenever possible.

Hence, use:

grep 'x{2,6}' example.txt

This deals with getting a regex to grep. Now we need to consider what it means. By default, this means look for the characters x, {, 2, ,, 6, } on a single line. Adding the -E option uses extended regular expressions, and the command looks for anything from 2 to 6 consecutive x's on a single line in the file:

grep -E 'x{2,6}' example.txt

However, it might be worth noting that this is pretty much the same as selecting 'xx' unless you have colouration on, or are selecting 'only' the matched text (the GNU grep extension -o option).

These are all for 2-6 adjacent x's, which is roughly what your proposed regex wanted.

You ask about three adjacent x's:

grep 'xxx' example.txt

The single quotes aren't 100% necessary, but they do no harm and remind you to use them for the regex in general.

Now we face the dilemma that you probably meant "between 2 and 6 x's on a single line, not necessarily adjacent, and not 0 or 1, nor 7 or more".

  • Rule 2: describe your required result precisely

Imprecise requirements lead to incorrect, or unintended, results. Meeting that requirement needs a more complex regex:

grep -E '^([^x]*x){2,6}[^x]*$' example.txt

That looks for 2-6 occurrences of zero or more non-x's followed by an x at the start of the line, followed by zero or more non-x's up to the end of line.

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174716

I need to display all the lines using GREP command that contain 2-6 'x's

grep -P '^(?:[^x]*x[^x]*){2,6}$' file

Also need to know how to display all lines with 3 consecutive 'x's

grep -P 'xxx' file

Upvotes: 2

Related Questions