mark
mark

Reputation: 5070

grep match lines with n leading spaces

I'm getting stuck on this one. I want to match all lines that start with exactly, say, 8 spaces and then a double quote mark.

cat file.txt | grep '[[:space:]]\{8\}"'

What am I doing wrong there? It's matching lines that start with more than 8 spaces also.

Upvotes: 10

Views: 28618

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85775

You don't need to pipe cat into grep just do egrep '^ {8}"' file the ^ character matches the start of the line so the pattern is anchored.

$ cat file
        "match"
        no match
   "no match"

$ egrep '^ {8}"' file
        "match"

The repetition quantifier {n} if part of the extended regular expression set so use egrep or alternatively use the -E option of grep to avoid escaping.

Upvotes: 6

Suku
Suku

Reputation: 3880

cat file.txt | grep '^[[:space:]]\{8\}"'

If you don't put ^, it will match 8 spaces which is near to your ".

Upvotes: 17

Related Questions