richsoni
richsoni

Reputation: 4278

Grep Regex to select last word including escaped spaces

I have the following grep command, which selects the last word of an outputted line.:

grep -o "[^ ]*$"

I am using this to select paths to filenames that are outputted by a program as the last word of the line like this:

~some stuff~ path

my issue is that if the path has escaped spaces "Some\ Word", then the regex will obviously only select "Word". Is there a way I can have it select spaces, but not escaped spaces?

Upvotes: 1

Views: 3518

Answers (2)

sp00m
sp00m

Reputation: 48837

You could use a positive lookbehind:

((?<=\\) |[^ ])+$

Upvotes: 0

Kent
Kent

Reputation: 195169

this would work for you:

grep -Eo '([^ ]|\\ )*$'

for example:

kent$  cat file
foo some\ word1
foo this word2
foo the\ whole\ word

kent$  grep -Eo '([^ ]|\\ )*$' file                                                                                                                                         
some\ word1
word2
the\ whole\ word

Upvotes: 2

Related Questions