在Linux中运行一些命令读取或编辑字符串或文件中文本时,经常会去尝试输出过滤到感情的特定部分,这时候就可以应用正则表达式。Awk是一个强大文本处理工具,支持正则表达式,能用于过滤和处理文本数据,下面是华纳云分享的awk正则表达过滤文本或字符串的实例。
正则表达可以定义为多个字符序列的字符串,正则表达最重要是允许过滤命令或文件的输出、编辑文本或配置文件的某个部分等。Awk是一种编程语言,使用中可以作为一个命令行过滤器。一般语法:
awk 'script' filename
其中是一组awk'script'可以理解并在文件 filename 上执行的命令。工作原理是读取文件中给定行,复制该行,再执行该行上的脚本。这个操作在文件的全部行上重复。其'script'形式为,模式'/pattern/ action'是一个正则表达式,而操作是 awk 在某一行中找到给定模式时将执行的操作。
Linux中使用awk工具,将打印文件/etc/hosts中的所有行。
awk' // {print}'/etc/hosts
用 Awk 模式:匹配文件中带有“localhost”的行
在下面的例子中,localhost给出了一个模式,因此 awk 将匹配文件中包含localhost 的/etc/hosts行。
awk' /localhost/ {print}'/etc/hosts
在模式中使用带 (.) 通配符的 Awk。在以下示例中,(.)将匹配包含loc、localhost、localnet的字符串。也就是说* l some_single_character c *:
awk ' /lc/ {print}'/etc/hosts
在模式中使用带有 (*) 字符的 Awk。它将匹配包含localhost、localnet、lines、able 的字符串,如下例所示:
awk ' /l*c/ {print}'/etc/localhost
它(*)会尝试为您获取它可以检测到的最长的匹配项。
让我们看一个可以证明这一点的案例,采用正则表达式t*t,表示匹配以字母开头t并以字母结尾的字符串,t如下所示:
this is tecmint, where you get the best good tutorials, how to's, guides, tecmint.
当你使用该模式时,你将获得以下可能性/t*t/:
this is t
this is tecmint
this is tecmint, where you get t
this is tecmint, where you get the best good t
this is tecmint, where you get the best good tutorials, how t
this is tecmint, where you get the best good tutorials, how tos, guides, t
this is tecmint, where you get the best good tutorials, how tos, guides, tecmint
且(*)通配符/t*t/允许 awk 选择最后一个选项:
this is tecmint, where you get the best good tutorials, how to's, guides, tecmint