Mike Q
Mike Q

Reputation: 7327

Print lines with JUST grep on a string and nothing more?

Using grep, can I search for something in a file and just get the lines which contain the string and not additional lines which contain other text? In the example below (as a simplification) I want to print the lines with password = and not password = [:alnum:]. I am not sure how to do this. I kind of need grep because I am actually capturing more than just this line but I am excluding this larger command from my question.

File with data:

    password = Mike
    password = Jessica
    password = 
    password = Sofi
    password = Maya
    password = 

Prints:

    password = 
    password = 

Upvotes: 0

Views: 1294

Answers (4)

tripleee
tripleee

Reputation: 189397

grep -F -x 'password =' file

The -F is a minor tweak to disable regex matching and only match literal strings. The -x specifies that the entire line must match.

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74615

Using grep with extended regular expressions (note that egrep is deprecated):

grep -E '=\s*$' file

This ensures that after the equals sign, there is only whitespace before the end of the line.

Alternatively, assuming that they're all space characters (no tabs, for example):

grep '= *$' file

You could also use the POSIX whitespace character class:

grep '=[[:space:]]*$' file

If you need to also ensure that the word "password" is on the line as well:

grep -E 'password\s*=\s*$' file

Upvotes: 0

Vince
Vince

Reputation: 3395

You can use regular expression with egrep and invert the match with -v:

grep -E -v 'password = \S+' file

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53525

You can use $ (end of line) to make sure there's no additional text:

grep '^password =\s*$' file

Upvotes: 1

Related Questions