2010-07-14 71 views
61

我在使用grep類型的工具來搜索純粹的文字字符串。我正在尋找一行日誌文件的出現,作爲單獨日誌文件中行的一部分。搜索文本可以包含各種正則表達式特殊字符,例如[]().*^$-\Grep for literal strings

是否有一個Unix搜索實用程序不會使用正則表達式,而只是搜索字符串的字面值?

+0

想知道爲什麼問題不是_「我可以讓'grep'搜索文字串嗎?」_而不是_「是否有像'grep'這樣的可以搜索文字串的東西?」_平頭螺絲刀可以安裝飛利浦螺絲釘頭,您知道';)' – ADTC 2017-12-02 21:14:15

回答

88

您可以使用grep,並使用-F選項。

​​
+0

*「換行符分隔的固定字符串」*我如何在終端提示符下執行此操作?我知道我可以創建一個模式文件,但沒有文件,是否可以在提示符上執行?按Enter鍵顯然執行該命令。 – ADTC 2015-12-07 09:21:07

+3

*我會回答我自己的問題。 :)*您只需要使用'-e'選項的重複提供多個固定字符串。像這樣:'grep -F -e「fixed1」-e「fixed2」-e「fixed3」-e「fixed4」'。不需要換行符;) – ADTC 2015-12-07 09:30:38

+1

在Solaris上不可用。而是使用'fgrep'。 – majkinetor 2016-06-17 11:29:46

2

通過-Fgrep

7

這要麼fgrepgrep -F這不會做正則表達式。 fgrep是相同的grep -F但我更喜歡不用擔心爭論,本質上是懶惰:-)

grep -> grep 
fgrep -> grep -F (fixed) 
egrep -> grep -E (extended) 
rgrep -> grep -r (recursive, on platforms that support it). 
+0

對於GNU grep,fgrep只是作爲符號鏈接提供給grep,這使得它需要-F – Daenyth 2010-07-14 02:12:48

+3

'egrep'和'fgrep '不是由POSIX標準規定的; 'grep -F'和'grep -E' [是](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html) – 2012-01-31 21:20:24

3

你也可以用awk,因爲它必須找到固定的字符串,以及編程的能力功能,例如,僅

awk '{for(i=1;i<=NF;i++) if($i == "mystring") {print "do data manipulation here"} }' file 
0
cat list.txt 
one:hello:world 
two:2:nothello 

three:3:kudos 

grep --color=always -F"hello 

three" list.txt 

輸出

one:hello:world 
three:3:kudos 
+1

這對現有的接受答案沒有增加任何內容。 – 2016-03-09 12:03:41

+0

我不同意。它是如何工作的一個有用的例證。 – timwaagh 2017-09-05 12:44:18