Jury A
Jury A

Reputation: 20062

How can I egrep this expression

I have a text file with the following strings, each in a separate line

Host: 22.44.55.33 (x.y.z)   Status: Up

what I need to extract from lines is the string between the brackets x.y.z .

How can I do this using grep in Linux?

Upvotes: 0

Views: 89

Answers (2)

Igor Chubin
Igor Chubin

Reputation: 64563

echo "Host: 22.44.55.33 (x.y.z)   Status: Up" | egrep -o "\([^)]*\)"
(x.y.z)

The re \([^)]*\) means that you need (, then any symbols except ) and then ). The -o key of grep says that grep needs to print only that part of the input text that matches the regular expression.

If you want only that lines that have "Host: Up" inside, you can use assertions:

$ cat 1.txt 
(1.2.3.4) Host: Up
(5.6.7.8) Host: Down
(9.1.2.3) Host: Up

$ grep -oP '\([^)]*\)(?=.*Host: Up)' 1.txt
(1.2.3.4)
(9.1.2.3)

The main point here is (?=.*Host: Up) that says that you want Host: Up in the line.

Upvotes: 4

legoscia
legoscia

Reputation: 41568

You need sed, not egrep - sed can edit the text, while egrep can only choose lines of text and print them unchanged. Something like this:

sed -e 's/^Host:.*(\([^)]*\)).*$/\1/' < inputfile.txt

Upvotes: 2

Related Questions