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?
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?
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.
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.If you always want the second part of the path, try this
echo "/sample/xyz/logs/test.logs" | awk -F/ '{print $3}'