47

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


I need to get only the lines from a textfile (a wordlist, separated with newline) that has a length range of minimum or equal than 3 characters, but not longer or equal than 10.

Example:

INPUT:

egyezményét
megkíván
ki
alma
kevesen
meghatározó

OUTPUT:

megkíván
alma
kevesen

Question: How can I do this in bash?

2
  • 11
    grep -x '.\{3,10\}'
    – Costas
    Feb 12, 2015 at 18:22
  • 1
    @Costas brilliant, and the same goes for sed as well. Post a complete answer.
    – orion
    Feb 12, 2015 at 18:26

5 Answers 5

68
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)
1
  • This solution inspired an additional usage which can be useful, see answer I posted below. May 27 at 16:36
14

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.

5

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
1
  • Excellent solution, much better to remember than the dark magic that is regex. Nov 27, 2020 at 2:45
2

Using sed:

sed '/^.\{3,10\}$/!d'

Or:

sed -r '/^.{3,10}$/!d'
0

I think this will be useful to someone. By extension, if you want to match a specific string within a line that is no longer than say 255 characters, this would be a solution.

Usage: looking for a string but wanting to exclude long lines like minified JS files which you didn't write or don't need

grep -x '.\{1,255\}theStringIWant.\{1,255\}'

A bit of a hack as you can't really control the length on both ends to be no more than a certain number (it could be 1 and 255, 255 and 1, or 255 and 255) but this works in most cases to exclude minified long lines

BASH NEWBIE TIP: the \ backslashes are escape characters for the {} braces.

Example/Proof:

echo "aaaalocalStoragebbbbccccdd" | grep -x '.\{3,10\}localStorage.\{3,10\}' #works
echo "aaaalocalStoragebbbbccccdddd" | grep -x '.\{3,10\}localStorage.\{3,10\}' #doesn't work, dddd puts end string to 12 chars

Your Answer

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