fgrep命令

fgrep命令

當需要搜索包含很多正則表達式元字符的字符串時,例如$^等,fgrep很有用,其通過指定搜索字符串包含固定字符,從而無需對每個字符進行轉義用反斜槓,如果搜索的字符串包含換行符,則每行將被視爲要在搜索中匹配的單個固定字符字符串。也就是說fgrep是用來搜索固定字符的,固定字符表示字符串是按字面意義解釋的-元字符不存在,因此不能使用正則表達式,運行fgrep與使用-F選項運行grep效果相同。

語法

fgrep [-b] [-c] [-h] [-i] [-l] [-n] [-s] [-v] [-x] [ -e pattern_list] [-f pattern-file] [pattern] [file]

參數

  • -b: 在每一行前面加上找到該行所在的塊號,這在根據上下文(第一個塊爲0)定位塊號時非常有用。
  • -c: 只打印包含模式的行數。
  • -h: 搜索多個文件時禁止打印文件。
  • -i: 在比較時忽略大小寫的區別。
  • -l: 打印一次具有匹配行的文件名稱,用換行分隔,當模式出現多次時,不會重複文件名。
  • -n: 在文件中,在每一行前面加上它的行號(第一行是1)。
  • -s: 靜默工作,也就是說只顯示錯誤消息,這對於檢查錯誤狀態非常有用。
  • -v: 打印除包含模式的行以外的所有行。
  • -x: 僅打印完全匹配的行。
  • -e pattern_list: 在pattern list中搜索字符串,當字符串以-開頭時很有用。
  • -f pattern-file: 從模式文件中獲取模式列表。
  • pattern: 指定在搜索輸入期間使用的模式。
  • file: 要搜索模式的文件的路徑名,如果沒有指定文件參數,將使用標準輸入。

示例

hello.c文件內容如下:

#include <stdio.h>
#include <stdlib.h>

int main() {
   printf("Hello World\n");
   printf("Hello World\n");
   printf("Hello World\n");
   return 0;
}

匹配帶有Hello的行。

fgrep Hello hello.c
#    printf("Hello World\n");
#    printf("Hello World\n");
#    printf("Hello World\n");

匹配帶有Hello行的數量。

fgrep -c Hello hello.c
# 3

反轉匹配的意義,選擇不匹配Hello的行。

fgrep -v Hello hello.c
# #include <stdio.h>
# #include <stdlib.h>
#
# int main() {
#    return 0;
# }

匹配帶有i的行並忽略大小寫。

fgrep -i I hello.c
# #include <stdio.h>
# #include <stdlib.h>
# int main() {
#    printf("Hello World\n");
#    printf("Hello World\n");
#    printf("Hello World\n");

僅輸出與文件整行匹配的行。

fgrep -x "   return 0;" hello.c
#    return 0;

匹配帶有Hello的行並輸出行號。

fgrep -n Hello hello.c
# 5:   printf("Hello World\n");
# 6:   printf("Hello World\n");
# 7:   printf("Hello World\n");

遞歸匹配當前目錄下所有文件中能夠匹配h*的文件,請注意由於使用fgrep,命令是不會匹配*的模式,而是將其作爲固定字符*去匹配,所以此時是沒有匹配的,如果使用grep以及相同的參數,則能夠輸出行號並忽略大小寫,注意實際在終端中匹配成功的位置會使用紅色字體標註。

fgrep -rni "h*" ./
# [輸出爲空]

每日一題

https://github.com/WindrunnerMax/EveryDay

參考

https://www.computerhope.com/unix/ufgrep.htm
https://www.runoob.com/linux/linux-comm-fgrep.html
https://www.geeksforgeeks.org/fgrep-command-in-linux-with-examples/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章