I'm using nslookup -q=srv SOME_ADDRESS, and want to store the returned addresses inside an array. nslookup returns:

Server:   123.456.789.123
Address:  123.456.789.123#12

SOME_ADDRESS  service = 0 0 1234 address-1.i.want.
SOME_ADDRESS  service = 0 0 1234 address-2.i.want.
SOME_ADDRESS  service = 0 0 1234 address-3.i.want.

I'm still learning regex, I got the strings into an array with:

array=($(nslookup -q=srv SOME_ADDRESS | grep -o ' [a-z0-9.-]*[a-z0-9].$'))

which gives me [ ]address-3.i.want. where the [ ] is a white-space.

How would I match only adress-3.i.want without the space at the start and . at the end? (with regex, not by removing characters from the result string. I know how to do it adding another grep or cut via pipes, but I'm sure I could just edit the regex to do what I want)

2 Answers 2


Task can be done by GNU sed

nslookup -q=srv "${SOME_ADDRESS}" | 
sed -n '/\.$/s///;T;/.* /s///p' | 
mapfile -t array

In sed

  • -n do not print lines on default
  • /\.$/s/// remove "." in the end of line
  • T go to end (mean print nothing if action above didn't took place)
  • /.* /s///p remove everething untill and print remain

or non-GNU

sed -n '/ /s//\n/;/\n/D;s/\.$//p'
  • / /s//\n/ substitute by newline
  • /\n/D remove all upto newline and begin from the start
  • s/\.$//p if remove "." in the end of line print resedue
  • I would really appreciate if you explain a bit
    – Rahul
    Aug 12, 2016 at 11:32

To match a period, you must either escape it or include it between square brackets. To exclude the initial space, simply don't add it to the regex at all (you run in the risk of selecting text after an invalid character other than a space though). Finally, there is no need to include the digits selection more than once if you use + (i.e. at least one match) instead of * (zero or more matches) followed by a specified match:

array=nslookup -q=srv SOME_ADDRESS | grep -o '[a-z0-9.-]\+\.$'

Note that the regex above would exclude capitalised characters and underscores. If you need them, you can use [:alnum:] as well as the valid symbols.

array=nslookup -q=srv SOME_ADDRESS | grep -o '[[:alnum:]_.-]\+\.$'
  • Thank you for the response. Ah yes, the . should be \. I executed your regex, it still includes the "." at the end into the matched string. I wish to exclude that from the match itself. (find the string before "\.$" ). Aug 12, 2016 at 9:02
  • 3
    @user3193260 grep -oP '\S*(?=\.$)' if you have pgrep
    – Costas
    Aug 12, 2016 at 10:32
  • @Costas: Thank you, this solved my problem Aug 12, 2016 at 10:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .