I have a string of IP and port numbers which is like : "10.213.110.49.33482;10.213.106.12.20001:
"
The two ip's are separated by a semi-colon. Last decimal shows port number.
What I need is to convert the above string which would look like:
"10.213.110.49 20001:
".
I want to remove the middle octets and port number of first IP using SHELL SCRIPT only. I want to extract the IP from first part ignoring the port number and from second IP i want the port number only
Asked
Active
Viewed 209 times
-1

Prashant Kumar
- 2,057
- 2
- 9
- 22
-
http://stackoverflow.com/questions/428109/extract-substring-in-bash – Harsha W Mar 31 '17 at 06:57
-
*of first IP* - should the second IP be ignored OR the first IP must derive some parts of the second IP??? Make it more clear – RomanPerekhrest Mar 31 '17 at 06:58
-
I want to extract the IP from first part ignoring the port number and from second IP i want the port number only. – Prashant Kumar Mar 31 '17 at 07:10
-
What do you mean by "SHELL SCRIPT only"? You have tags for e.g. sed, so it would be OK to call sed from shell? – Yunnosch Mar 31 '17 at 07:20
-
Yeah, I dont want solutions with python or any other language. I can use sed, awk, substitution or whatever I can use in a shell script @Yunnosch – Prashant Kumar Mar 31 '17 at 07:25
3 Answers
1
using sed:
sed 's/\.[0-9]*;.*\.\([0-9]*:\)/ \1/' <<< \
'10.213.110.49.33482;10.213.106.12.20001:'
gives:
10.213.110.49 20001:

perreal
- 94,503
- 21
- 155
- 181
-
Thankyou sir @perreal. Working absolutely fine and is a good solution. Really helpful :) – Prashant Kumar Apr 05 '17 at 06:53
-
You don't need the back references at all, just remove that part and replace with a space – grail Apr 05 '17 at 08:26
0
awk solution:
s="10.213.110.49.33482;10.213.106.12.20001:"
echo $s | awk -F"[.;]" '{OFS=".";print $1,$2,$3,$4" "$10}'
The output:
10.213.110.49 20001:

RomanPerekhrest
- 88,541
- 4
- 65
- 105
0
You can just use bash substitution, just takes a couple of steps:
s='10.213.110.49.33482;10.213.106.12.20001:'
port="${s##*.}"
ip="${s%;*}"
ip="${ip%.*}"
echo "$ip $port"

grail
- 914
- 6
- 14
-
-
-
# removes from the start and % removes from the end. If you double either it removes from the same direction until the last occurrence. So ${s#*.} would remove from the front up until first period, but ${s##*.} would remove all up until the last period in the string – grail Oct 05 '17 at 11:49