Unix sed command - extract text between 2 slashes

Viewed 87

apologies for a basic question using sed, I have been trying to work it out but my brain fails me...

I am trying to extract the text between two slashes within some unix shell.

I would like to extract the text between the 3rd and 4th slash (DEV). I have been trying to contruct the the following but without success..

echo "/share/test/DEV/2021-05-21/out/9988776_948016287_1.PDF" |
sed 's|\(.3\)/.4|\1|'

Any help greatly appreciated.

Many thanks M

4 Answers

It should be an easy task with awk, try following. Simply setting field separator to / and printing 4th field as per output required.

echo "/share/test/DEV/2021-05-21/out/9988776_948016287_1.PDF" | awk -F'/' '{print $4}'

With sed you can try following:

echo "/share/test/DEV/2021-05-21/out/9988776_948016287_1.PDF" | 
sed -E 's/^\/[^/]*\/[^/]*\/([^/]*)\/.*/\1/'

OR

sed -E 's_^/[^/]*/[^/]*/([^/]*)/.*_\1_' Input_file

Use

path="/share/test/DEV/2021-05-21/out/9988776_948016287_1.PDF"
IFS='/' read -ra arr <<< "$path"
echo ${arr[3]}  

Results: DEV.

Same results with path="/dir with space/test/DEV/2021-05-21/out/9988776_948016287_1.PDF".

cut -d/ -f4

-d for the delimiter, -f4 for the 4th item (the 1st is presumed to be empty)

This might work for you (GNU sed):

sed -nE 's#^(([^/]*)/){4}.*#\2#p' file

Extract the fourth field from a record delimited by /'s.

Related