Why is PCRE grep treating forward slashes as whitespace?

76 Views Asked by At

On bash, I'm trying to get the uppercase letter immediately after a whitespace (A from File A.jpg).

echo "Path/To/File A.jpg" | grep -oP '[A-Z](?!/s)'

This is a negative lookahead (?! that should return any uppercase after a whitespace. So, it should return only A. However, it's returning all upercases:

P
T
F
A

It seems it's treating forward slashes as whitespaces? Why? How can I get only the last A?

2

There are 2 best solutions below

0
matt On BEST ANSWER

should return any uppercase after a whitespace

No, that’s not what it says at all. It says “any uppercase not followed by forward slash and s.” Well none of them are followed by that. So you get all the uppercase characters.

What you want is a positive lookbehind.

(?<=\s)[A-Z]
0
The fourth bird On

Using grep with -P you can match a horizontal whitespace char using \h and, as also pointed out in the comments, you can use \K to clear the match buffer and then match a single uppercase char A-Z.

echo "Path/To/File A.jpg" | grep -oP '\h\K[A-Z]'

Output

A