Use grep to find strings at the beggining of a line or after a delimiter in Git Bash for Windows

I have such file:

blue|1|red|2
green|3|blue|4
darkblue|0|yellow|3

I want to use grep to find anything containg blue| at the beginning of line or |blue| anywhere, but not any darkblue| or |darkblue| or |blueberry|

I tried to use grep [^|\|]blue\| but Git Bash gives me error:

$ grep [^|\|]blue\| *.*
grep: Unmatched [ or [^
sh.exe": |]blue|: command not found

What did I do wrong? What's the proper way to do it?

Answers


Here's a quick & dirty one:

grep -E '(^|\|)blue\|' *

Matches start of line or |, followed by blue|. The important note is that you need extended regular expressions (via egrep or the -E flag) to use the | (or) construct.


Also, note the single quotes around the regular expression.

So, in answer to the OP's "What did I do wrong?",

  1. You forgot to put the regexp in single quotes;
  2. You chose the wrong type of brackets to enclose the alternate expressions; and finally
  3. You forgot to use egrep or the -E flag

It's always easier to see other people's errors; I wish I was a quick to spot my own :-|


Need Your Help

Remove quotes from named environment variables in Windows scripts

windows batch-file scripting environment-variables quotes

I want to store a URL prefix in an Windows environment variable. The ampersands in the query string makes this troublesome though.

RegEx to match text and enclosing braces

regex vb.net

I need to loop through all the matches in say the following string:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.