Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a statement of the form atPhysAddress[1][] 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
up vote 1 down vote accepted

For example with

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

To only get the first number in the second bracket:

$ echo "atPhysAddress[1][]" | sed 's/.*\]\[\([^.]*\).*\]/\1/'
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][]" | 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][]" | sed -r 's/\[([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\]/[XX.\2.XX.XX.XX]/'
share|improve this answer

Your Answer


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.