Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a statement of the form atPhysAddress[1][1.10.0.0.98] i would like to remove all details except for the first one in the second bracket, or whichever value falls there, how can i achieve this?(i.e i would like to only leave out the first integer in the second bracket)

share|improve this question

2 Answers 2

up vote 1 down vote accepted

For example with

$ echo "atPhysAddress[1][1.10.0.0.98]" | sed 's/\(\[.*\]\)\[\(.\).*\]/\1[\2]/'
atPhysAddress[1][1]

To only get the first number in the second bracket:

$ echo "atPhysAddress[1][12.10.0.0.98]" | sed 's/.*\]\[\([^.]*\).*\]/\1/'
12
share|improve this answer
    
is it possible to have only the second 1 –  sosytee Sep 20 '13 at 12:25
    
@sosytee: if you mean that you only want the single char in the second pair of brackets, you can have it with echo "atPhysAddress[1][1.10.0.0.98]" | sed 's/.*\]\[\(.\).*\]/\1/' –  enzotib Sep 20 '13 at 13:14
    
@enzotib: while you're at it, can you please also show how this first "value" can be captured even when it consists of several digits before the first dot? –  Sadi Sep 20 '13 at 15:23
    
@sosytee: see updated answer –  enzotib Sep 20 '13 at 19:08

You could do something like

sed -r 's/\[([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\]/[XX.\2.XX.XX.XX]/'

which matches [ followed by a sequence of 5 dot-separated integers followed by ] and then resubstitutes the 2nd (with XX marking the removed ones - optional of course). The use of the -r option makes the expression easier to read but you could re-write it in POSIX sed if GNU sed is not available. By changing \2 to \1, \3, \4 etc. you can choose which number to re-substitute.

echo "atPhysAddress[1][1.10.0.0.98]" | sed -r 's/\[([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\]/[XX.\2.XX.XX.XX]/'
atPhysAddress[1][XX.10.XX.XX.XX]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.