views:

118

answers:

3

Bash script

I have a string:

tcp 6 0 CLOSE src=111.11.111.111 dst=222.22.222.22 sport=45478 dport=5000 packets=7 bytes=474 src=111.11.111.111 dst=222.22.222.22 s port=5000 dport=45478 packets=8 bytes=550 [ASSURED] mark=0 use=1

I need cut src IP addr 111.11.111.111, how?

+3  A: 

Here's a quick and dirty way to do it: Pipe it through sed, like this:

sed -e 's/.*src=\([^ ]*\).*/\1/'
scott_karana
thanks it works, regs is too hard for me :)
bymaker
+2  A: 

You don't need an external tool for this one. If you're getting the string from a command output, as seems likely, you want

string="$(command)"
string="${string#* src=}"
string="${string%% dst=*}"

First line captures all the output. Second line cuts off the shortest prefix ending in src=. Third line cuts off the longest suffix ending in dst=.

Shell globbing is way easier than regexps!

Norman Ramsey
A: 

you can use awk. the snippet below gets all src ip, not just one instance of it.

<command> | awk '{for(i=1;i<=NF;i++){if($i~/src/){sub("src=","",$i);print $i}}}'
ghostdog74