3

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?

3
  • 1
    Please clarify. Do you just always want the second part of the path, the xyz in your 2 examples?
    – Lewis M
    Oct 10, 2018 at 12:32
  • @LewisM just want the second path. Oct 10, 2018 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 Oct 10, 2018 at 12:35

3 Answers 3

6

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.

2

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.
0
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.