I am using a regular expression with grep. I want to extract exactly 7 character passwords, but I am getting 7 and more than 7 characters as a result.

grep '[a-zA-Z0-9]\{7\}' /usr/share/wordlists/rockyou.txt

grep '[a-zA-Z0-9]\{7,7\}' /usr/share/wordlists/rockyou.txt

Use extended grep:

grep  -E '^[a-zA-Z0-9]{7}$' /usr/share/wordlists/rockyou.txt

or your own version like:

grep '^[a-zA-Z0-9]\{7\}$' /usr/share/wordlists/rockyou.txt

or even:

egrep '^.{7}$' /usr/share/wordlists/rockyou.txt

Any line that contains more than 7 characters also contains a substring of 7 characters (which will match your expression).

You can force only complete matches by anchoring the expression to the start and end of the line:

grep '^[a-zA-Z0-9]\{7\}$' /usr/share/wordlists/rockyou.txt

or specify whole-line matching using the -x option

grep -x '[a-zA-Z0-9]\{7\}' /usr/share/wordlists/rockyou.txt

From man grep:

-x, --line-regexp
       Select  only  those  matches  that exactly match the whole line.
       For a regular expression pattern, this  is  like  parenthesizing
       the pattern and then surrounding it with ^ and $.

you can cd to the directory and try the below command:

grep ^.......$ *
  • . --> any single character (so seven . is seven characters)
  • * (asterisk) --> all the files in the current directory (except, usually, those whose names begin with a literal .). You can give the file name(s) too if preferred.
  • As explained in steeldriver's answer, this will not work because all lines with more than seven characters will also match.
    – Zanna
    Jan 29 '21 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.