天天看點

grep中的正規表達式

grep是Linux中用于處理檔案的工具之一。grep搜尋輸入檔案,查找與正規表達式比對的行,并将每個比對的行标準輸出。

正規表達式是比對一組字元串的模式。模式由操作符、構造文字字元和具有特殊意義的元字元組成。grep支援三種正規表達式文法:Basic、Extended和perl相容。

如果沒有提供正規表達式類型,grep将搜尋模式解釋為基本的正規表達式。要将模式解釋為擴充的正規表達式,請使用-E。

文字比對

grep指令最基本的用法是搜尋檔案中的文字字元或字元序列。例如,要顯示/etc/passwd檔案中包含字元串“bash”的所有行,需要運作以下指令:

[root@localhost ~]# grep bash /etc/passwd

root:x:0:0:root:/root:/bin/bash

bob:x:1000:1001::/home/bob:/bin/bash

user01:x:1001:1002::/home/user01:/bin/bash

grep中的正規表達式grep中的正規表達式

預設情況下,grep指令是區分大小寫的。這意味着大寫和小寫字元被視為不同的。要在搜尋時忽略大小寫,請使用-i選項。

如果搜尋字元串包含空格,則需要用單引号或雙引号将其括起:

[root@localhost ~]# grep "System message bus" /etc/passwd

dbus:x:81:81:System message bus:/:/sbin/nologin

錨點

^符号比對行首的空字元串。在下面的示例中,字元串“root”隻有在行首出現時才比對。

[root@localhost ~]# grep '^root' /etc/passwd

$要查找以字元串“bash”結尾的行,可以使用以下指令:

[root@localhost ~]# grep 'bash$' /etc/passwd

您還可以使用兩個錨來構造正規表達式。例如,檢視配置檔案,不顯示空行,請運作以下指令:

[root@localhost ~]# grep -v '^$' /etc/samba/smb.conf

-v 反轉比對的意義,來選擇不比對的行。

|符号

| 是或者的意思。例如:想檢視cpu是否支援虛拟化:

[root@localhost ~]# grep 'vmx|svm' /proc/cpuinfo

flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ssbd ibrs ibpb stibp tpr_shadow vnmi ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec arat md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities

如果使用擴充正規表達式,則不需要轉義|,如下所示:

https://article.pchome.net/content-2112034.html https://www.51cto.com/it/news/2020/0525/20939.html https://www.csdn.net/article/a/2020-05-20/15991626

[root@localhost ~]# grep -E 'svm|vmx' /proc/cpuinfo

總結

正規表達式用于文本編輯器、程式設計語言和指令行工具,如grep、sed和awk。在搜尋文本檔案、編寫腳本或過濾指令輸出時,了解如何構造正規表達式非常有用。

繼續閱讀