Print numbers from file, from x to y

2019-09-10 10:36发布

I've got a file with numbers from -100 to 100, I only want to print from -10 to 10

Currently, I'm at

egrep '[0-9][0-3]'

Which, unfortunately, prints -13, -12, -11, -10, 10, 11, 12, 13, 20, 21, 22, 23.

标签: linux unix grep
3条回答
Lonely孤独者°
2楼-- · 2019-09-10 10:56
egrep '^-?10$|^-?[0-9]$'

this is basically two regexs one to get 10,-10 and one to get all the singular numbers

查看更多
Evening l夕情丶
3楼-- · 2019-09-10 11:04

Have a try with that regular expression:

^[-]?(10|[0-9])$

So the call on CLI would be:

egrep "^[-]?(10|[0-9])$" testfile

Why?

  • start with an optional leading "-"
  • followed by either:
    • literal number "10" or
    • single digit between 0 and 9
  • and nothing behind that
查看更多
Anthone
4楼-- · 2019-09-10 11:10

This is not about egrep, since from your comments it seems you don't want egrep for its own sake here are some alternatives:

  1. use seq: seq first inc last

    seq -15 1 14 will print all numbers between -15 to 14 each on his own line

  2. use awk: awk '{ if ($1 >= first && $1 <= last) print $1 }' filename

    awk '{ if ($1 >= -15 && $1 <= 14) print $1 }' numbers.txt will print all numbers between -15 to 14 each on his own line

  3. use perl: perl -lane 'print $_ if $_ >= first && $_ <= last' filename

    perl -lane 'print $_ if $_ >= -15 && $_ <= 14' numbers.txt will print all lines between -15 to 14 each on his own line

hope it helps

查看更多
登录 后发表回答