0

I have a file with lines in the following pattern:

136x2340+1564+0

that is, <N1>x<N2>+<N3>+<N4>.

I'd like to filter (maybe with grep) all lines such that N1 range is from a to b and N2 range is from c to d.

The constants a,b,c,d depend on my problem. I'll fix them in the script.

I tried egrep '^([0-9][0-9][0-9]x[0-9][0-9][0-9]+)' but the output shows

136x2340+1564+0
835x428+355+1780
817x406+186+747
114x1533+1256+456

that is, also shows lines with N2 with 4 digits (I supposed only 3 digits).

edit: also I'd like to replace x by , (comma), the first + sign by (empty space) and the second + sign by , (comma) so the output should be

N1,N2 N3,N4

1 Answer 1

2

In grep extended regular expression (ERE) syntax, + is a quantifier meaning 'one or more of the preceding atom'. To match + literally in this context, you need to escape it:

egrep '^([0-9][0-9][0-9]x[0-9][0-9][0-9]\+)' file
835x428+355+1780
817x406+186+747

If you want to make substitutions, then grep really isn't the right tool - however if your version of sed has a similar extended regex mode you could use that:

sed -En 's/([0-9]{3})x([0-9]{3})\+([0-9]{1,})\+([0-9]{1,})/\1,\2 \3,\4/p' file
835,428 355,1780
817,406 186,747

If you only have basic regular expressions, the escaping becomes harder to read:

sed -n 's/\([0-9]\{3\}\)x\([0-9]\{3\}\)+\([0-9]\{1,\}\)+\([0-9]\{1,\}\)/\1,\2 \3,\4/p' file
835,428 355,1780
817,406 186,747
5
  • scape!!! How could I forget it?? Thanks so much. So easy! Commented Nov 29, 2016 at 0:02
  • please, could you see edited post? Commented Nov 29, 2016 at 0:13
  • Perfect. Now you saved my day. -En works good. Commented Nov 29, 2016 at 0:28
  • How to filter if lower bound a contains 3 digits and upper bound b could contain 3 or 4. In other words, I'd like to filter now any line such that N1xN2 belongs to Cartesian region [150,1100] x [200,1200]? Commented Nov 30, 2016 at 12:24
  • 1
    @Sigur you should probably switch to a tool that supports arithmetic (rather than strictly lexical) comparisons - such as awk or perl Commented Nov 30, 2016 at 18:36

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.