Issue
I'd like to know how to take the following string
/text1/text2/text3/wanted_text/text5/text6
and get the wanted text, based solely on its position between the 4th and 5th /
?
Solution
A substitution command is enough (I've obviously assumed that the interesting part is between the 4th and 5th /
as you said):
echo your_text | sed -E 's!(/[^/]+){3}/([^/]+).*!\2!'
where I've used !
as separator for the parts of the s
ubstitution command, in order to avoid having to escape every /
.
More in detail:
s!…!…!
is the seach-and-substitute command, where you put the search pattern in the first…
and the replacement in the second…
;- the seach pattern is
(/[^/]+){3}/([^/]+).*
and matches 3 occurrences of a/
followed by 1 or more non-/
, followed by a/
followed by 1 ore more non-/
; the(…)
are for grouping a part of a regex such that you can apply quatifiers (like{3}
) to the whole group (just like in(/[^/]+){3}
), and for capturing the matching text to allow you to refer to it in the replacement; in this case, the third of the 3 texts matching(/[^/]+){3}
is referred to via\1
, whereas the text matched by([^/]+)
is referred to via\2
; - the replacement is simply
\2
(see previous point).
For more details about how the search pattern works, and to understand all of its parts, you can refer to this demo on regex 101.
(-E
is a non-POSIX-compliant option that makes the script more readable. Without it, you have to prepend \
to each of (
, )
, {
, }
and +
.)
Answered By - Enlico Answer Checked By - David Marino (WPSolving Volunteer)