Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminal output command pipe to input of grep and using regular expression?

Tags:

regex

grep

pipe

I thought getting an IP address on OSX or Linux would be rather easy to learn how to use regular expression with grep, but it looks like I either have a syntax error or misunderstanding of what is required.

I know this regex is correct, although I know it may not be a valid IP address I'm not considering that at this point.

(\d{1,3}\.){3}\d{1,3}

so I'm not sure why this doesn't work.

ifconfig | grep -e "(\d{1,3}\.){3}\d{1,3}"
like image 248
Sn3akyP3t3 Avatar asked Mar 29 '13 23:03

Sn3akyP3t3


People also ask

How do you pipe a grep output?

grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".

How do you pipe the output of a command to another command?

You can make it do so by using the pipe character '|'. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.

Can you use regex with grep?

You can also use the grep command to search for targets that are defined as patterns by using regular expressions. Regular expressions consist of letters and numbers, in addition to characters with special meaning to grep . These special characters, called metacharacters, also have special meaning to the system.

What command do you use to search for regular expressions in a text file?

In addition to word and phrase searches, you can use grep to search for complex text patterns called regular expressions.


1 Answers

Two things:

First, there is a difference between -e and -E : -e just says "the next thing is an expression", while -E says: "use extended regular expressions". Depending on the exact version of grep you are using, you need -E to get things to work properly.

Second, as was pointed out before, -d isn't recognized by all versions of grep. I found that the following worked: since ip addresses are "conventional" numbers, we don't need anything more fancy than [0-9] to find them:

ifconfig | grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}'

No need to escape other characters (in my version of grep - using OSX 10.7.5)

Incidentally, when testing your regular expression you can consider using something like

echo "10.1.15.123" | grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}'

to confirm that your regex is working - regardless of the exact output of ifconfig. It breaks the problem into two smaller problems, which is usually a good strategy.

like image 120
Floris Avatar answered Sep 25 '22 19:09

Floris