LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   copy certain text (https://www.linuxquestions.org/questions/programming-9/copy-certain-text-743683/)

pr0xibus 07-29-2009 08:41 AM

copy certain text
 
Is it possibly to copy certain text from a file

i have a script that will configure my wireless card $interface
and i would like it to grap the mac address of the $interface so i thought

ifconfig $interface > add.txt

but since it will say alot of things in there when i type ifconfig including the mac address is it possible just to get a certian part i.e. search a file for **:**:**:**:**:** then put it in a var called $mac

Thanks

colucix 07-29-2009 08:50 AM

Quote:

Originally Posted by pr0xibus (Post 3624240)
is it possible just to get a certian part i.e. search a file for **:**:**:**:**:** then put it in a var called $mac

Yes, you can build a regular expression to match the MAC address and use egrep -o to get the result, e.g something like
Code:

mac=$(/sbin/ifconfig eth0 | egrep -o \([0-9A-Z][0-9A-Z]:\)\{5\}[0-9A-Z][0-9A-Z])
but more simply you can do something like
Code:

mac=$(/sbin/ifconfig eth0 | awk '/HWaddr/{print $NF}')
since the MAC address is the last field of the line containing "HWaddr".

vonbiber 07-29-2009 08:58 AM

Quote:

Originally Posted by pr0xibus (Post 3624240)
and i would like it to grap the mac address of the $interface so i thought

ifconfig $interface > add.txt

put it in a var called $mac

do you mean the ip address?
here's what my 'ifconfig wlan0' displays:
ifconfig wlan0
wlan0 Link encap:Ethernet HWaddr 00:21:5d:b2:e5:96
inet addr:10.62.11.219 Bcast:10.62.11.223 Mask:255.255.255.224
UP BROADCAST NOTRAILERS RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1630626 errors:0 dropped:0 overruns:0 frame:0
TX packets:1040182 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:2140727532 (1.9 GiB) TX bytes:243190342 (231.9 MiB)

The IP address can be seen in the line with 'inet addr:...'

If I want to store the IP address into a variable, I'd go this
way:
1. make sure the interface is up (ifconfig wlan0 up)
2. make sure the IP address has been attributed
if [ $(ifconfig wlan0 | grep -c 'inet addr:') -eq 0 ]; then
#no ip address found
... exit the script ...
fi
3. the ip address exists, store it in the variable mac:
mac=$(ifconfig wlan0 | grep 'inet addr:' | sed 's?.*inet addr:\([0-9][.0-9]*\).*$?\1?')

4. check:
echo $mac
should display:
10.62.11.219

replace wlan0 by the name of your interface if it's different

pr0xibus 07-29-2009 08:58 AM

colucix you my friend are a LEGEND


All times are GMT -5. The time now is 02:03 PM.