bash awk 打印以正则表达式开头的行(IP 地址)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39306393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:08:26  来源:igfitidea点击:

Awk print lines starting with regex (IP address)

linuxbashshellawksed

提问by Karthik

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

我正在尝试为那些在第一列上具有 IP 地址的行读取文件。

my command below does not return any value.

我下面的命令不返回任何值。

cat test.csv | awk ' == "^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}]" { print 
cat test_1.csv | awk '~/^[[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\]/ {print 
1.1.1.1 ipaddress gateway
2.2.2.2 ipaddress_2 firewall
www.google.com domain google
}'
}'

The regex can capture IP address.

正则表达式可以捕获 IP 地址。

Tried the below too,

也尝试了以下,

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

test.csv

测试文件

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

回答by redneb

You can do it more easily with grep:

您可以更轻松地使用grep

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

or

或者

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

回答by sat

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

当您{1,3}在 GNU 中使用(Interval expressions) 时awk,您必须使用任一--re-interval(或)--posix选项来启用它。

Use :

用 :

##代码##

(OR)

(或者)

##代码##

From man awk:

来自man awk

r{n,m}

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

r{n,m}

大括号内的一两个数字表示区间表达式。只有在命令行中指定了--posix--re-interval 时,间隔表达式才可用。