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?

don_crissti
  • 82,805

3 Answers3

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.

glenn jackman
  • 85,964
joker
  • 594
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.
choroba
  • 47,233
0

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

echo "/sample/xyz/logs/test.logs" | awk -F/ '{print $3}'
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Lewis M
  • 1,048