Difference between grep pattern ^$ and ^

9,106

Solution 1

The grep man page explains both symbols:

Anchoring
The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line.

Searching for ^ just matches the beginning of the line, which every line has, so they all match. Searching for an empty string has no constraints at all, so it also matches all lines. Searching for ^$ means "match the beginning of the line followed by the end of the line", which is a blank line. You can also use them for cases like finding all lines that start with foo (^foo), or all lines that end with bar (bar$)

Solution 2

^ is for the beginning of a line.

^$ is saying beginning of a line, end of a line $, with nothing in between.

using this regex you can find blank lines and delete/exclude blank line

eg.

grep -Ev '^$|^#'  /etc/sudoers

It will exclude blank line and line which is start from hash ( # )

Share:
9,106

Related videos on Youtube

user3539
Author by

user3539

Updated on September 18, 2022

Comments

  • user3539
    user3539 over 1 year

    I understand that grep matches all the blank lines for the pattern ^$. But what does just ^ mean? When I gave grep '^' filename, it matched all the lines.

    Also grep '' filename matched all the lines.