idd=$(npm run server "$domain" | sed -n -E '$s+id/(.*)$+\1+p')
I piped npm's output to sed, like you did in your second snippet. The -E
flag, which you also used, enables extended regexes. Those aren't even needed here now that I think of it, but it's kind of standard because EREs are more useful.
-n
tells sed to by default not print its buffer when going to the next line. It does more or less the same as when you'd use d
on every input line after all other commands. When using -n
you have to explicitly ask sed to print certain lines, with the p
command – but that's actually not used here, as we'll shortly see!
The $
will make sure that the command is only executed on the last line of the input.
The s
command is the replacement command. You can use any character right after it and that will be s
's delimiter. The classic is /
but here I've used +
since we are using a /
in the needle and this way we don't have to escape the /
. id/(.*)$
is the needle and \1
is the replacement. You don't have to anchor your strings like you do, so a needle of ^(.*)id/(.*)$
and corresponding replacement \2
is equivalent but redundant (and will most likely impose a slight performance overhead).
Because there's no semicolon after s
, p
is actually not a separate command here, but a flag to s
. It will print the buffer iff the s
command was successful in finding something to replace.