Nahshon paz
Nahshon paz

Reputation: 4573

sed or grep to read between a set of parentheses

I'm trying to read a version number from between a set of parentheses, from this output of some command:

Test Application version 1.3.5

card 0: A version 0x1010000 (1.0.0), 20 ch

Total known cards: 1

What I'm looking to get is 1.0.0. I've tried variations of sed and grep:

command.sh | grep -o -P '(?<="(").*(?=")")'

command.sh | sed -e 's/(\(.*\))/\1/'

and plenty of variations. No luck :-(

Help?

Upvotes: 2

Views: 121

Answers (3)

David C. Rankin
David C. Rankin

Reputation: 84551

There are a couple of variations that will work. First with grep and sed:

grep '(' filename | sed 's/^.*[(]\(.*\)[)].*$/\1/'

or with a short shell script:

#!/bin/sh

while read -r line; do
    value=$(expr "$line" : ".*(\(.*\)).*")
    if [ "x$value" != "x" ]; then 
        printf "%s\n" "$value"
    fi
done <"$1"

Both return 1.0.0 for your given input file.

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157967

Having GNU grep you can also use the \K escape sequence available in perl mode:

grep -oP '\(\K[^)]+'

\K removes what has been matched so far. In this case the starting ( gets removed from match.

Alternatively you could use awk:

awk -F'[()]' 'NF>1{print $2}'

The command splits input lines using parentheses as delimiters. Once a line has been splitted into multiple fields (meaning the parentheses were found) the version number is the second field and gets printed.


Btw, the sed command you've shown should be:

sed -ne 's/.*(\(.*\)).*/\1/p'

Upvotes: 1

choroba
choroba

Reputation: 241848

You were almost there! In pgrep, use backslashes to keep literal meaning of parentheses, not double quotes:

grep -o -P '(?<=\().*(?=\))'

Upvotes: 3

Related Questions