Home > Uncategorized > Grepping for N occurances of a string or character within a line:

Grepping for N occurances of a string or character within a line:

The following will grep for one backslash in a line:

grep "^[^\\]*\\[^\\]*$" du_report.log

The following will grep for three backslashes in a line:

grep "^[^\\]*\\[^\\]*[^\\]*\\[^\\]*[^\\]*\\[^\\]*$" du_report.log

The following will grep for one, two, or three backslashes in a line:

grep "^[^\\]*\\[^\\]*[^\\]*\\[^\\]*[^\\]*\\[^\\]*$\|^[^\\]*\\[^\\]*[^\\]*\\[^\\]*$\|^[^\\]*\\[^\\]*$" du_report.log

A comment by Lee, also suggest using extended grep commands:

grep -E ‘\\{1,3}’ du_report.log

^ = beginning of line regex character
[^\\] = beginning of line regex character followed by a backslash
* = any character
\\ = backslash
$ = end of line regex character

References:

Advertisements
  1. lee
    July 9, 2013 at 10:45 am

    You might also check out the ‘-E’ option to grep:

    grep -E ‘\\{1,3}’ du_report.log

    Will grep for one, two or three back slashes (it will also catch four, five etc, but is a starting point for tweaking)

    • July 9, 2013 at 12:24 pm

      Great! Seems very powerful thanks.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: