LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Shell script:- Reading numbers embedded in brackets from a text file (http://www.linuxquestions.org/questions/linux-newbie-8/shell-script-reading-numbers-embedded-in-brackets-from-a-text-file-737807/)

rsan 07-05-2009 04:27 AM

Shell script:- Reading numbers embedded in brackets from a text file
 
Hi,
I need to extract two numbers (variable in length) from a fixed pattern in a text file.
The pattern is like this:

Word1(123456) Word2(678923) Word3(987)

Now from above pattern I need to simply extract 123456, 678923 and put them in two variables using a shell script (bash).

I exhausted all options including using sed, cut, awk but could not find a suitable answer.

Please help.

Thanks.

rsan 07-05-2009 05:05 AM

I have got following working - but only managed to extract first number yet:

var=`cat test`
echo Readinf file
count=0
startCount=0
for readLine in $var; do
echo $readLine > tmprrs1
while [ ${readLine:count:1} ]
do
if [ ${readLine:count:1} = '(' ]
then
startCount=`expr $count + 2`
echo $startCount
fi
if [ ${readLine:count:1} = ')' ]
then
endCount=`expr $count`
echo $endCount
var1=`cut -c $startCount-$endCount tmprrs1`
echo "First var: " $var1
fi
#advance the counter to read the next character in the string i
count=`expr $count + 1`
done
done

Tinkster 07-05-2009 05:08 AM

Hi,

Welcome to LQ!


Firstly: those are parentheses, not brackets.

And please show us what you've done e.g. with sed and awk,
since those are perfectly suitable tools for the job.

How are they failing for you?


Cheers,
Tink

rsan 07-05-2009 05:25 AM

Re
 
Ok - this one I've done with following changes:


var=`cat test`
count=0
startCount=0
for readword in $var; do
echo $readword > tmprrs1
while [ ${readword:count:1} ]
do
if [ ${readword:count:1} = '(' ]
then
startCount=`expr $count + 2`
echo $startCount
fi
if [ ${readword:count:1} = ')' ]
then
endCount=`expr $count`
echo $endCount
var1=`cut -c $startCount-$endCount tmprrs1`
echo "First var: " $var1
fi

count=`expr $count + 1`
done
count=0
startCount=0
done

rsan 07-05-2009 05:26 AM

Re
 
with sed, awk many adhoc commands - none worked. any suggestions?

ghostdog74 07-05-2009 06:00 AM

Code:

awk '
{
 for(i=1;i<=2;i++){
    gsub(/.*\(|).*/,"",$i)
    print $i
 }
}' file


colucix 07-05-2009 06:01 AM

You did not show the attempts with sed and awk. If you can post them, we can tell you where the error was. In the meanwhile, you can be interested in reading http://www.grymoire.com/Unix/Sed.html


All times are GMT -5. The time now is 06:04 PM.