Using grep to find string with brackets

北战南征 提交于 2021-01-27 02:36:19

问题


I have some problems with the grep command. I have the following two files in my folder:

test.dat:

fdf
bla(fd_bla_bla) =&
bdf bla

test2.dat

fd
fd
fij
d
bla(fdf)

fdjk
bla

Now I search for the bla having brackets after it with

grep 'bla(*)' *

but it just gives me the entry of the first file...Do you have an idea why?


回答1:


You need regular expressions to do that match.

egrep "bla\(.*\)" *.dat

will give the correct result.




回答2:


your grep 'bla(*)' * won't work, because it looks for bla) or bla(((((((() that is , 0 or many ( after bla then followed by single )

just do:

grep '\bbla(' *.dat
  • by default grep uses BRE, so ( in pattern would match literal (
  • the \b (word boundary) will make grep match foo bla(..) and bla(xx), but not foobla(xxx).



回答3:


grep -F "bla(" 

This will tell grep to use special characters as a regular (Fixed) string.




回答4:


You just need .* instead of *

In Regex .* matched any arbitrary string of 0 or more length. * is used by shell GLOB to match a text of arbitrary search but grep doesn't use GLOB.

grep 'bla(.*)' *.dat

OR for word boundaries:

grep '\<bla(.*)' *.dat

OR using awk:

awk '/bla\(.*\)/{print FILENAME ":" $0}' *.dat



回答5:


Another solution is that, if your string is fixed string and it contains brackets. so with the help of grep -F you can make your string fixed and it will be search as it is. cat enb.txt | grep -F '[PHY][I]UE'** cat enb.txt is the file name where i want to catch. grep -F '[PHY][I]UE' grep -F make the string this '[PHY][I]UE' Fixed.

try this i hope it will work




回答6:


perl -lne 'print if(/bla\(.*\)/)' your_file



回答7:


$ grep "bla(" *

should work. ( need not be escaped as it indicates grouping in regex which we don't need it .

$ cat > test7
fdf
bla(fd_bla_bla) =&
bdf bla


$ cat > test8
fd
fd
fij
d
bla(fdf)

fdjk
bla

$ grep "bla(" *
test7:bla(fd_bla_bla) =&
test8:bla(fdf)


来源:https://stackoverflow.com/questions/18890348/using-grep-to-find-string-with-brackets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!