LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   sed/awk/cut/grep.. looking for the best solution (https://www.linuxquestions.org/questions/programming-9/sed-awk-cut-grep-looking-for-the-best-solution-866210/)

voda87 03-03-2011 07:15 AM

sed/awk/cut/grep.. looking for the best solution
 
Hi,
Im looking for a way to get variables out of a string..
There are a few forms that the string can be inputed by the user- thats the problem.
i need to seperate the string into 3 vars.. ($first $sign $second)
a few examples:

"name=jack"
"year>1980"
"age<25"
"name>abcd"
"price=59.99"

ok, you get the idea.. the first(left) part of the string will always be a word. The middle(sign) can only be: < , > , = .
and the third(right) part can be a number or a word, as described at the example. if the third part is a word it will do a string compare.

I need to execute an IF statement out of the string i get.
so im trying to first store each part of the string so i can know whats going on before writing the statement.

Thanks a lot for the helpers- any idea will B welcome!

David the H. 03-03-2011 07:38 AM

Using only variables and parameter substitution:
Code:

string="name=jack"

first="${string%[=><]*}"

sign=${string//[^=><]}

second="${string#*[=><]}"

echo "first: $first"
echo "sign: $sign"
echo "second: $second"

Note that this all assumes that there will always be exactly one instance of =,>,< in the string.

voda87 03-03-2011 07:43 AM

thanks!
 
wow what a quick reply.. thx it looks great.. ill give it a try

voda87 03-03-2011 07:54 AM

Great
 
works 100% , problem solved!
Thanks 10x

EricTRA 03-03-2011 07:59 AM

Hi,

Been playing around with this one and looks like it works.
File contains
Code:

test=exit1
test2<exit2
test3>exit3

Using a command like this:
Code:

cat test | awk -F'=|<|>' '{ print $2 , $1 }'
give this result:
Code:

exit1 test
exit2 test2
exit3 test3

as expected. Hope it's useful.

Kind regards,

Eric


All times are GMT -5. The time now is 08:21 AM.