Karthik
Karthik

Reputation: 363

Awk print lines starting with regex (IP address)

Im trying to read a file for those lines which has IP address on the first column.

my command below does not return any value.

cat test.csv | awk '$1 == "^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}]" { print $0 }'

The regex can capture IP address.

Tried the below too,

cat test_1.csv | awk '$1~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/ {print $0}'

test.csv

1.1.1.1 ipaddress gateway
2.2.2.2 ipaddress_2 firewall
www.google.com domain google

Upvotes: 1

Views: 12107

Answers (2)

sat
sat

Reputation: 14949

When you use {1,3} (Interval expressions) in GNU awk, you have to use either --re-interval (or) --posix option to enable it.

Use :

awk --posix '$1 ~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/' file

(OR)

awk --re-interval '$1 ~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/' file

From man awk:

r{n,m}

One or two numbers inside braces denote an interval expression. Interval expressions are only available if either --posix or --re-interval is specified on the command line.

Upvotes: 0

redneb
redneb

Reputation: 23860

You can do it more easily with grep:

grep -P '^\d+(\.\d+){3}\s' test.csv

or

grep -P '^\d{1,3}(\.\d{1,3}){3}\s' test.csv

Upvotes: 5

Related Questions