Evgheni Antropov
Evgheni Antropov

Reputation: 73

sed with regexp for different situations

I have a simple task:

From such output:

[root@localhost:~]# racoonctl -s /var/racoon/racoon.sock ss isakmp
Destination            Cookies                           Created
89.208.102.86.500      d0a641ed0aa7bfe9:7ae3428b08fab146 2013-02-04 15:32:18

need to take only IP address string and date string (in different requests).

For IP I have wrote following regexp:

[root@localhost:~]# racoonctl -s /var/racoon/racoon.sock ss isakmp | sed -ne 's/^\(\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\).*/\1/p'
89.208.102.86

But for date doesn't work

[root@localhost:~]# racoonctl -s /var/racoon/racoon.sock ss isakmp | sed -ne 's/^.*\([0-9]\{4\}\(\-[0-9]\{2\}\)\{2\}\  \([0-9]\{2\}:\)\{2\}[0-9]\{2\}\)$/\2/p'
[root@localhost:~]# 

Can not understand where is the error?

Also I want to change /(expression/) and /{expression/} using flag -r, but have no idea how will do it

Thank you in advance

P.S. also I know about alternative variant:

[root@localhost:~]# racoonctl -s /var/racoon/racoon.sock ss isakmp |awk -F\. '/[0-9]/ {print $1"."$2"."$3"."$4}' 
89.208.102.86

[root@localhost:~]# racoonctl -s /var/racoon/racoon.sock ss isakmp | awk '/[0-9]/ {print $3 " " $4}'
2013-02-04 15:32:18

But I want to do it on sed, for my future hadrly tasks.

Upvotes: 1

Views: 143

Answers (4)

erik
erik

Reputation: 2446

For IP like 1.2.3.4 it is:

sed -n 's%\([0-9.]+\).*%\1%p'
sed -rn 's%([0-9.]+).*%\1%p'

and for date it is:

sed -n 's%.*\ \([0-9-]\+\ [0-9:]\+\)%\1%p'
sed -rn 's%.* ([0-9-]+ [0-9:]+)%\1%p'

And if the IP is always like 1.2.3.4.5 (so, has a fifth field which obviously is the port number) the sed command is:

sed -n 's%\([0-9.]\+\)\.[0-9]\+.*%\1%p'
sed -rn 's%([0-9.]+)\.[0-9]+.*%\1%p'

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246774

Assuming there's no whitespace in the cookies, a simple while read loop will do:

racoonctl ... | while read -r ip cookies date; do
    # do something with "ip" and "date"
    echo $ip
    echo "$date"
done

If you want to throw away the header line

racoonctl ... | {
    read header
    while read -r ip cookies date; do
        # do something with "ip" and "date"
        echo $ip
        echo "$date"
    done
}

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

How about:

# IP 
$ sed -rn '2s/\.[0-9]+ .*//p' file
89.208.102.86

# Date and time
$ sed -rn '2s/(\S+\s+){2}//p' file
2013-02-04 15:32:18

# Just date
$ sed -rn '2s/(\S+\s+){2}(\S+).*/\2/p' file
2013-02-04

Upvotes: 1

anubhava
anubhava

Reputation: 785058

You can use following sed:

sed -ne 's/^.*\([0-9]\{4\}\(\-[0-9]\{2\}\)\{2\} \)/\1/p'

to get your date.

Upvotes: 1

Related Questions