Get everything on line but match with grep

2

I'm trying to get everything on the matched line excluding the match using grep.

If I have

#define VERSION 0.1

The command should echo

0.1

I saw this question, but I only want things on the same line.

I read the man page, but I don't see anything that matches my specific usage case. Would a different command possibly be better than grep for this?

Zach Latta

Posted 2013-03-06T14:44:16.143

Reputation: 159

So you're searching for #define VERSION? – Dennis – 2013-03-06T14:45:02.077

Yeah. What I'm specifically doing is executing a shell command to get what VERSION is defined as and storing it in a macro in a Makefile. – Zach Latta – 2013-03-06T14:46:01.540

Answers

2

An easy way to achieve this is piping grep's output to sed:

command | grep "^#define VERSION" | sed 's/^#define VERSION //'

You can achieve the same result using only sed if you use the -n switch and the p (i.e., print) pattern for the regular expression. This will replace and only print lines that have been modified:

command | sed -n 's/^#define VERSION //p'

See: man sed

Dennis

Posted 2013-03-06T14:44:16.143

Reputation: 42 934

1

If your version of grep supports perl regex you can do it like this:

grep -oP '(?<=#define VERSION )[^ ]*$'

Otherwise use two invocations of grep:

grep '#define VERSION' | grep -o '[^ ]*$'

Thor

Posted 2013-03-06T14:44:16.143

Reputation: 5 178