Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need RegExp help for Linux Bash grep command to filter out lines containing square brackets

Using the following example, I need to filter out the line containing 'ABC' only, while skipping the lines matching 'ABC' that contain square brackets:

2012-04-04 04:13:48,760~sample1~ABC[TLE 5332.233 2/13/2032 3320392]:CAST
2012-04-04 04:13:48,761~sample2~ABC
2012-04-04 04:13:48,761~sample3~XYZ[BAC.CAD.ABC.CLONE 232511]:TEST

Here is what I have, but so far I'm unable to successfully filter out the lines with square brackets:

bash-3.00$ cat Metrics.log | grep -e '[^\[\]]' | grep -i 'ABC'

Please help?

like image 968
Alexander Len Avatar asked Apr 05 '12 13:04

Alexander Len


People also ask

How do you grep square brackets in Linux?

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.

What do square brackets mean in grep?

Since the grep process itself has "firefox" in it, grep finds that as well. By adding a [] , we are only searching for the character class "[f]" (which consists of only the letter "f" and is therefor equivalent to just an "f" without the brackets).

How do you escape a grep bracket?

If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter. To match a character that is special to grep –E, put a backslash ( \ ) in front of the character.

Can you grep a command output?

Using Grep to Filter the Output of a CommandA command's output can be filtered with grep through piping, and only the lines matching a given pattern will be printed on the terminal. You can also chain multiple pipes in on command. As you can see in the output above there is also a line containing the grep process.


1 Answers

Edited based on comments:

Try grep -i 'ABC' Metrics.log | grep -v "[[]" | grep -v "ABC\w"

Input:

2012-04-04 04:13:48,760~sample1~ABC[TLE 5332.233 2/13/2032 3320392]:CAST
2012-04-04 04:13:48,761~sample2~ABC
2012-04-04 04:13:48,761~sample3~XYZ[BAC.CAD.ABC.CLONE 232511]:TEST
2012-04-04 04:13:48,761~sample4~XYZ
2012-04-04 04:13:48,761~sample5~ABCD
2012-04-04 04:13:48,761~sample6~ABC:TEST

Output:

2012-04-04 04:13:48,761~sample2~ABC
2012-04-04 04:13:48,761~sample6~ABC:TEST
like image 114
GetSet Avatar answered Oct 02 '22 07:10

GetSet