Home > other >  how to list a range of numbers in file
how to list a range of numbers in file

Time:02-10

I have a file named example.txt and inside the file I have numbers from 1 -50 but I only want to view number within a particular range like 1-25

I tried this command: less example.txt | grep [1-25]

but this didn't help, please help

CodePudding user response:

[1-25] means match group of characters consisting of characters between 1 and 2 and character 5. It's the same as [125] - match any of 1 2 or 5.

You can:

grep '[1-9]\|1[0-9]\|2[0-5]'

Match digits 1 to 9, or match 1 followed by digit 0 to 8, or match 2 followed by digit 0 to 5. Maybe add -w, see man grep.

I recommend regex crosswords for learning regex.

CodePudding user response:

IMHO the best way would be to use mathematical condition check rather than regex, please try following awk program.

awk '$0>=0 && $0<=25' Input_file

Above will work if your lines are containing only digits eg:

1
2
3
.....

In case your Input_file's lines can contain multiple digits that you want to print then better to loop through them and apply conditions to them and print them then.

awk '{for(i=1;i<=NF;i  ){if($i>=0 && $i<=25){print $i}}}' Input_file
  • Related