You misuse \K
, it discards the matched text captures until current moment, it has no use at the beginning of the pattern. +file1
is consuming pattern, it will be returned as a match part.
Use non-consuming pattern:
grep -m 1 -oP "\w+(?=\s+$file\b)" a.file
See regex proof. \b
will disallow matching file10
.
EXPLANATION
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
file1 'file1'
--------------------------------------------------------------------------------
\b the boundary between a word char (\w)
and something that is not a word char
--------------------------------------------------------------------------------
) end of look-ahead