LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   How to use grep, cut, or awk to get an IP from a file (https://www.linuxquestions.org/questions/linux-general-1/how-to-use-grep-cut-or-awk-to-get-an-ip-from-a-file-786732/)

chudster 02-03-2010 12:37 PM

How to use grep, cut, or awk to get an IP from a file
 
Hello, I am new to shell scripting. I have a file which contains a line like this:

SERVER=10.205.110.19

How can I cut out the IP and assign it to a variable?

Thanks.

EricTRA 02-03-2010 12:41 PM

Hello,

Two simple possibilities:
Code:

cat yourfile | awk -F= '{ print $2 }'
or
Code:

awk -F= '{ print $2 }' < yourfile
Kind regards,

Eric

EricTRA 02-03-2010 12:44 PM

Oops, sorry, rereading your post I imagine the file contains more lines than just the SERVER one; so small adjustment:
Code:

cat yourfile | grep "SERVER" | awk -F= '{ print $2 }'
Darn, must be getting tired, forgot the assignment to the variable:
Code:

VARIABLE=`cat yourfile | grep "SERVER" | awk -F= '{ print $2 }`
Kind regards,

Eric

tuxdev 02-03-2010 01:35 PM

If it's literally just a bunch of VAR=VALUE, and you want all the VALUEs to get shoved into their respective VARs, then you can just "source" the file. Be aware that's actually just the same as copying and pasting the contents of the file to where the "source" directive is, so weird things you might not have expected otherwise might have happened.

Another approach like EricTRA's is to do:
Code:

SERVER="$(grep "SERVER=" "$FILE")"
SERVER="${SERVER#*=}"


chrism01 02-03-2010 07:06 PM

Code:

echo SERVER=10.205.110.19 |cut -d'=' -f2


All times are GMT -5. The time now is 09:44 AM.