Filter lines based on length using sed and grep

How to locate lines longer than 100 and smaller than 150 characters using sed and grep

2 Answers

Using sed command

sed -nr '/^.{101,149}$/p' infile

Breaking down:

  • -n: no printing

The -n option will prevent to print anything unless an explicit request to print is found (^.{101,149}$ "Lines longer than 100(>=101) and smaller than 150 characters(<=149)"). The /p flag used as one way to turn printing back on.

  • -r: -r (--regexp-extended)

The -r enables the Extended regular expressions. replace -r with -E if your sed doesn't recognize it or you will need to escape the curly braces if none of them supported in your version of sed. Then the command would be sed -n '/^.\{101,149\}$/p' infile.

  • The ^ is just the anchor for beginning of line and the $ for end of line.

  • A single . matches any single character

So, you got it, with sed -nr '/^.{101,149}$/p' infile, we are looking for a line from start to end of it which has or contains our defined rule.

This is a way to duplicate the function of grep with sed e.g: sed -n '/.../p' :)

Using grep command

grep -E '^.{101,149}$' infile
  • -E this is the same as sed's -r option but for grep command. So if you don't want to use is just escape the curly braces.

Using awk command

awk 'length($0)>100 && length($0)<150' infile
  • length return the length of the line. In awk, the $0 specifies the whole line. So if the length of line was between 100 and 150, will be print out.
4

Another way of doing this using bash:

while read l; do nc=$(<<< "$l" wc -c); [ $nc -ge 101 ] && [ $nc -le 149 ] && echo "$l"; done < file

Expanded into a script:

#!/bin/bash
while read l; do nc=$(<<< "$l" wc -c) if [ $nc -ge 101 ]; then if [ $nc -le 149 ]; then echo "$l" fi fi
done < file
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like