0

I have the following grep

grep "/abc/[A-Z]" file1.txt | cut -d/ f3 | sort -u

The grep worked perfectly returning the results,

ALPHA
abc
BRAVO
CHARLIE

However, why is the abc in the output too? I have made the regex to only take capitalize words after the delimiter backslash. Is this an intended output and how should I remove the abc from the output?

5
  • grep prints the full line. grep -o prints the matching part only. Which would be e.g. /abc/A here, not /abc/ALPHA.
    – ilkkachu
    Commented Oct 9, 2021 at 12:25
  • Thanks both. What will be a good strategy to get the desired result? Commented Oct 9, 2021 at 12:27
  • If the expected output is what you have above without abc, then you'll need to add sample text to your question so that we have an idea of what you are working with. Commented Oct 9, 2021 at 12:34
  • 1
    Your command as posted looks wrong. cut f3 reads a file called f3. You probably used cut -f3. Also, if you want the whole name to be uppercase, you need a repeat on the character range, and a terminator, like [A-Z]+$: your pattern only examines the first character of the field. Commented Oct 9, 2021 at 15:18
  • Read the current comments carefully and edit if needed.
    – number9
    Commented Oct 9, 2021 at 21:44

1 Answer 1

0

You have not anchored the regular expression that you use with grep. A consequence of this is that it may match anywhere on the line.

A line saying, e.g.,

blah/blah/abc/Abc

or

/blah/abc/Abc

would match your expression, and both would contain the string abc as the 3rd /-delimited field.

To anchor your expression to the start of the line, use

^/abc/[A-Z]

Alternatively, enforce a more strict match some other way, or weed out the abc result at the end using grep -v -F -x abc, whichever method suits your style and application the best.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .