0

This question already has an answer here:

How do I extract such pattern using sed?

This is my path: /sample/xyz/logs/test.logs

Output should be : xyz

How is that possible if the path keeps changing for example like

/example/xyz/log/test.logs?

using sed or awk?

marked as duplicate by don_crissti, user88036, RalfFriedl, Jeff Schaller, Romeo Ninov Oct 10 '18 at 19:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Please clarify. Do you just always want the second part of the path, the xyz in your 2 examples? – Lewis M Oct 10 '18 at 12:32
  • @LewisM just want the second path. – user6690412 Oct 10 '18 at 12:34
  • I tried this echo /sample/xyz/logs/test.logs | sed 's/log*//g' output: /sample/xyz/s/test.s this is the output that i get – user6690412 Oct 10 '18 at 12:35
0

If your script is bash/dash/ksh/zsh, you don't need any external tools, parameter substitution can give you the answer:

path=/sample/xyz/logs/test.logs
path=${path#/*/}
echo ${path%%/*}
  • # removes from the left.
  • % removes from the right.
  • doubling the character makes the matching greedy, i.e. it matches as much as it can.
1

I know 3 ways to do so. I'll assume the path is passed as stdin.

Method 1

echo "/sample/xyz/logs/test.logs" | cut -d / -f 3

This cuts the input with the delimiter specified with -d / and chooses the third field, which is the xyz part you want.

Method 2

echo "/sample/xyz/logs/test.logs" | awk -F / '{print $3}'

awk is a very powerful command that you can write quite complex logic with. You can use it in this simple form to do the same thing as method 1.

Method 3

echo "/sample/xyz/logs/test.logs" | sed -r 's/^\/\w+\/(\w+)\/.*/\1/g'

Using sed with regular expression, you omit the first slash, the word afterwards along with the following slash. Take the word that comes after the second slash then remove the rest.

As you can see, complexity increases over the methods.

0

If you always want the second part of the path, try this

echo "/sample/xyz/logs/test.logs" | awk -F/ '{print $3}'

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