How to "grep" for line length in a given range?

grep -x '.\{3,10\}'

where

  • -x match pattern to whole line
  • . any symbol
  • {3,10} quantify from 3 to 10 times previous symbol (in the case any ones)

using egrep

egrep '^.{3,10}$'

matches from begining to ending of lines for 3 or more character but less than or equal to 10 characters.


Using awk:

awk 'length >= 3 && length <= 10' file

The length statement would return the length of $0 (the current record/line) by default, and this is used by the code to test wether the line's length is within the given range. If a test like this has no corresponding action block, then the default action is to print the record.

Testing on the given data:

$ awk 'length >= 3 && length <= 10' file
megkíván
alma
kevesen

Similarly with Perl:

$ perl -lne '$l=length($_); print if ($l >= 3 && $l <= 10)' file
megkíván
alma
kevesen

Tags:

Bash

Perl

Grep

Sed