Grep for Line Length Not in Range – How to Use Regular Expressions

grepregular expressiontext processing

NOTE: This question is the complement of this Q&A: How to "grep" for line length in a given range?


How can we grep for lines that have less than 8 or more than 63 characters, none that contain more than eight and less than 63 characters?

So, some acceptable character counts could be…

7 6 5 4 3 2 1 0

…and…

64 65 66 67 ...

Best Answer

grep -xv '.\{8,63\}' <input >output

grep's -x switch denotes a whole line match - which is to say that any pattern matched must define a line from head to tail. doing...

grep -x pattern

...is generally equivalent to...

grep ^pattern$

grep's -v switch negates a pattern's influence on line-selection. generally doing...

grep pattern

...will only select lines that match the pattern, but with a -v negated pattern only those lines that don't match are selected.

...and so...

grep -xv '.\{8,63\}'

...matches all lines which consist from head to tail of anywhere between 8 and 63 characters, and the -v negated selection causes grep only to print everything else.

Related Question