-1

I have a file test.xml (shown below).  This grep works:

grep '<appointment-id internal:ref=1.2.3/>' test.xml

Output is:

    <appointment-id internal:ref=1.2.3/>

But this fails:

grep "$(grep '<appointment-id internal:ref=1.2.3/>' test.xml)" test.xml

Output is:

grep: invalid character range

Contents of test.xml:

<note>
    <to>Jim</to>
    <from>John</from>
    <heading>Reminder</heading>
    <body>Some text</body>
    <appointment-id internal:ref=1.2.3/>
</note>

I have put both grep commands (the simple one and the nested one) into a script with set -x.  Here is an exact copy & paste of that script:

set -x
grep '<appointment-id internal:ref=1.2.3/>' test.xml
grep "$(grep '<appointment-id internal:ref=1.2.3/>' test.xml)" test.xml
exit 0

and here is its output:

++ grep '<appointment-id internal:ref=1.2.3/>' test.xml
    <appointment-id internal:ref=1.2.3/>
+++ grep '<appointment-id internal:ref=1.2.3/>' test.xml
++ grep '    <appointment-id internal:ref=1.2.3/>' test.xml
grep: invalid character range
++ exit 0
Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233
Jim
  • 1,391

1 Answers1

6

Your (inner) grep produces colorized output, even though the output is not a terminal. It may do so when the GREP_COLOR environment variable is set to always.

The control codes to do the colorization contains characters that, when you feed them into the outer grep, are interpreted as character ranges.

When interpreted as character ranges, the pattern is invalid.

The solution is to disable colorization of the output from grep, either by explicitly using --color=never or by setting the appropriate environment variable (GREP_COLOR=never).

If you set GREP_COLOR=auto, grep should only produce colorized output when writing to a terminal, as is the case for the outer grep in your example, but not the inner grep.

Kusalananda
  • 333,661
  • But then isn't understanding the grep output more difficult if the actual search patter is not highlighted if we set the environment variable to never? – Jim Jun 07 '18 at 21:19
  • 2
    @Jim I can't say that I ever had that issue. I know what I grep for and when a line is returned from the file, I know that it has matched. This seems to be enough for me at least. If you set GREP_COLOR=auto, grep should only produce colorized output when writing directly to the terminal. This may be better for you, possibly. – Kusalananda Jun 07 '18 at 21:33