I need from this file extract line that starts with a number in the range 10-20 and I have tried use grep "[10-20]" tmp_file.txt, but from a file that has this format
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.aa
12.bbb
13.cccc
14.ddddd
15.eeeeee
16.fffffff
17.gggggggg
18.hhhhhhhhh
19.iiiiiiiiii
20.jjjjjjjjjjj
21.
it returned everything and marked every number that contains either 1, 0, 10, 2, 0, 20 or 21 :/
CodePudding user response:
With an extended regular expression (-E
):
grep -E '^(1[0-9]|20)\.' file
Output:
10.aa 12.bbb 13.cccc 14.ddddd 15.eeeeee 16.fffffff 17.gggggggg 18.hhhhhhhhh 19.iiiiiiiiii 20.jjjjjjjjjjj
See: The Stack Overflow Regular Expressions FAQ
CodePudding user response:
Assuming the file might not be sorted and using numeric comparison
awk -F. '$1 >= 10 && $1 <= 20' < file.txt
CodePudding user response:
An other one with awk
awk '/^10\./,/^20\./' tmp_file.txt
awk '/^10\./,/^13\./' tmp_file.txt
10.aa
12.bbb
13.cccc
CodePudding user response:
Using grep
$ for i in {10..20}; do grep "^$i\." input_file; done
10.aa
12.bbb
13.cccc
14.ddddd
15.eeeeee
16.fffffff
17.gggggggg
18.hhhhhhhhh
19.iiiiiiiiii
20.jjjjjjjjjjj
CodePudding user response:
Try
grep -w -e '^1[[:digit:]]' -e '^20' tmp_file.txt
-w
forces matches of whole words. That prevents matching lines like100...
. It's not POSIX, but it's supported by everygrep
that most people will encounter these days. Usegrep -e '^1[[:digit:]]\.' -e '^20\.' ...
if you are concerned about portability.- The
-e
option can be used multiple times to specify multiple patterns. [[:digit:]]
may be more reliable than[0-9]
. See In grep command, can I change [:digit:] to [0-9]?.
CodePudding user response:
grep is not the tool for this, because grep finds text patterns, but does not understand numeric values. Making patterns that match the 11 values from 10-20 is like stirring a can of paint with a screwdriver. You can do it, but it's not the right tool for the job.
A much clearer way to do this is with Perl:
$ perl -n -e'print if /^(\d )/ && $1 >= 10 && $1 <= 20' foo.txt
This says to print a line of the file if the beginning of the line ^
matches one or more digits \d
and if the numeric value of what was matched $1
is between the values of 10 and 20.