Sanket Gupte
Sanket Gupte

Reputation: 357

Use of grep "^d" in unix

I was preparing for a test when I came across a command/expression:

grep "^d" | wc -l

Can anyone please explain why this command is used?

Upvotes: 0

Views: 3855

Answers (5)

Shubham
Shubham

Reputation: 41

“^d” in Unix is also used as an indication of the directory.

grep "^d" | wc -l

This command can be used to count the number of the directory in a directory, like -

ls -lrth | grep "^d" | wc -l

To get the count of files only in a directory you can exclude "^d", like -

ls -lrth | grep -v "^d" | wc -l

Upvotes: 2

Ajeet Shah
Ajeet Shah

Reputation: 19823

grep prints lines that contain a match for a pattern.

So, grep "^d" | wc -l counts the number of lines starting with d.

Let's say I below lines in foo.txt:

dline1 abcd
dline2 abcd

line3 abcd
line4 abcd

dline5 abcd
dline6 abcd

So, when I run the below command:

cat foo.txt | grep "^d" | wc -l

It returns 4 because there are 4 lines (line-count) starting with d.

cat foo.txt returns the file content which is passed as input to grep "^d" which returns lines starting with d which is passed as input to wc -l which finally counts the lines in its input.

Upvotes: 0

neric
neric

Reputation: 4221

^ in a regular expression means 'at the beginning of a line'.

So yeah this will grep for any line starting with d

Note that in this case the expression should be: grep "^d" -c, -c for count matches, to avoid calling another binary.

Upvotes: 1

Fidel
Fidel

Reputation: 1037

grep "^d" | wc -l
string
string
dir
dir2
dir3
3 //Out of wc -l command (ie) grep catches only three lines which started with "d"

Execute above command looks for input from standard input after you pass "CTRL + D" which EOF, grep catches ( I would prefer grep greps :) ) only the line starting with "d" and wc -l counts the number of line the grep passes to it.

Basically, grep read from files, pipes and standard input. This is the third case.

Upvotes: 0

Bernhard
Bernhard

Reputation: 3694

This is used to count the amount of lines (in file or from a pipe) that start with a d.

I can imagine that it is used to count the amount of directories in a directory.

Upvotes: 1

Related Questions