Find the answer to your Linux question:
Results 1 to 3 of 3
I need to write a program that will take an x and y pair and extract out what x is equal to and what y is equal to. The pair ...
  1. #1
    Just Joined!
    Join Date
    Sep 2005
    Posts
    99

    regular expressions in bash

    I need to write a program that will take an x and y pair and extract out what x is equal to and what y is equal to. The pair can be entered in many different ways. A few ways include:

    x=2.0 y=2.3
    y=4.3 x=1.8
    or
    x = 2.0 y = 2.3
    y = 4.3 x = 1.8
    or
    x = 20; y = -30
    y = -5.3; x = 7.8
    or
    x -4.5 y -5.89
    Basically any combo you can think of x first, y first, space seperating, comma seperating semi colon seperating, space in between the = sign, no space in between = sign, no equal sign, negative numbers, positive numbers, integers, floating point numbers, if both x and y are the same it can be written as
    x=y=1.0
    y=x=1.20
    I think this can be done with regular expressions and grep, egrep, awk, sed, even though i don't understand any of those, nor do i understand any of the man pages for those either, but i think those are what i need to use. Anyone have any ideas of how to take the input entered like the above examples and get what the x is equal to and what the y is equal to from it?

  2. #2
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Quote Originally Posted by cwl157
    I think this can be done with regular expressions and grep, egrep, awk, sed, even though i don't understand any of those, nor do i understand any of the man pages for those either, but i think those are what i need to use.
    why didn't you try to learn how to use them then? at least try to come up with something.

  3. #3
    Just Joined!
    Join Date
    Apr 2007
    Posts
    6
    I guess something like this would work although I'm not the best perl scripter and there's probably lots to go wrong.

    #!/usr/bin/perl

    $i = 1;
    while(<>){
    print "Line: $i\n";
    if(/x( ?= ?)?(-?[0-9]+(\.[0-9]+)?)/){
    $x = $2; print "x = $x ";
    if(/^y( ?= ?)x/){
    $y = $x; print "y = $x";
    }
    }
    if(/y( ?= ?)?(-?[0-9]+(\.[0-9]+)?)/){
    $y = $2; print "y = $y ";
    if(/^x( ?= ?)y/){
    $x = $y; print "x = $y";
    }
    }
    print "\n";
    $i = $i + 1;
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...