LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Printing foremated output unto a variable using AWK (https://www.linuxquestions.org/questions/programming-9/printing-foremated-output-unto-a-variable-using-awk-931112/)

Regnets1 02-24-2012 03:25 PM

Printing foremated output unto a variable using AWK
 
I am trying to use AWK to search a text file and pull out a field. I want to take the output of the awk, strip off the first eleven characters and place that into a variable in a bash script.
The test script I am using for proof of concept is this:

Code:

#!/bin/bash

# test searching a file for an ip address based on an input variable

MSR=unset

echo "enter your PE router :"
read MSR

gawk -v pe="$MSR" '$1 == pe { print $NF }' lo1map
echo ""
echo ""
RD=$(gawk -v pe="$MSR" '$1 == pe { FS= "."} ; { print $5 }' lo1map)
sleep 3
echo "$MSR has a route descriptor of $RD"

this gives me an output of:
-bash-3.2$ ./greptest1
enter your PE router :
router1.nyr
192.168.0.50


router1.nyr has a route descriptor of

~~~~~~~~ several blank lines later~~~~~~~
66
53
78
62
70
69
79
58
68

What I am expecting for output is:
-bash-3.2$ ./greptest1
enter your PE router :
router1.nyr
192.168.0.50


router1.nyr has a route descriptor of 50

My input file lo1map looks like this (It's a lot longer though)

router1.ald 192.168.0.9
router1.bol 192.168.0.17
router1.chd 192.168.0.11
router1.dan 192.168.0.13
router1.dck 192.168.0.3
router1.den 192.168.0.15
router1.ft3 192.168.0.25
router1.lay 192.168.0.5
router1.mmd 192.168.0.19
router1.nyr 192.168.0.50


Thanks in advance!

corp769 02-24-2012 03:45 PM

Honestly, I think you went a bit overboard.....
Code:

#!/bin/bash

# test searching a file for an ip address based on an input variable

MSR=unset
INFILE=lo1map

echo "enter your PE router :"
read MSR

RD=$(grep $MSR $INFILE | awk -F. '{ print $5 }')

echo "$MSR has a route descriptor of $RD"

Cheers!

Josh

grail 02-24-2012 10:51 PM

Well my first question is why you set a variable to a string to then be overwritten later?
Code:

MSR=unset
My thought is you are trying to make sure the variable is not set which would be:
Code:

unset MSR
awk generally becomes clumsy when variables have to be used, so some other options are (using corp769's variable names):
Code:

RD=$(grep $MSR $INFILE | grep -Eo '[0-9]+$')

#or

RD=$(sed -n "/$MSR/s/.*\.//p" $INFILE)


Regnets1 03-01-2012 11:32 AM

thanks for the help, I went with the grep and awk option. i am very new to linux and bash scripting and I just don't have me head around SED yet.

thanks again for the quick responses!!


All times are GMT -5. The time now is 12:10 AM.