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' infileBreaking 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-Ethis is the same as sed's-roption but forgrepcommand. So if you don't want to use is just escape the curly braces.
Using awk command
awk 'length($0)>100 && length($0)<150' infilelengthreturn the length of the line. In awk, the$0specifies the whole line. So if the length of line was between 100 and 150, will be print out.
Another way of doing this using bash:
while read l; do nc=$(<<< "$l" wc -c); [ $nc -ge 101 ] && [ $nc -le 149 ] && echo "$l"; done < fileExpanded 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