How do I cut all characters after the last '/'?
This text
xxxx/x/xx/xx/xxxx/x/yyyyy
xxx/xxxx/xxxxx/yyy
should return
xxxx/x/xx/xx/xxxx/x
xxx/xxxx/xxxxx
How do I cut all characters after the last '/'?
This text
xxxx/x/xx/xx/xxxx/x/yyyyy
xxx/xxxx/xxxxx/yyy
should return
xxxx/x/xx/xx/xxxx/x
xxx/xxxx/xxxxx
If you want to get the "cutted part"
You can use
eg.
output
(Note: This uses the ability of sed to use a separator other than /, in this case |, in the s command)
If you want to get the begining of the string :
You can use
eg.
output
If you're cutting off the ends of the strings,
dirname
might fit the bill:If you're trying to isolate the last part of the string, use
echo /$(basename "$str")
.Parameter expansion in
bash
You can use parameter expansion in
bash
, in this case${parameter%word}
whereword
is/*
${parameter##word}
whereword
is*/
Examples:
Remove the last part
This is described in
man bash
:Remove all except the last part
You can add a slash like so
to get exactly what you wanted at one particular instance according to the edited question. But the question has been edited by several people after that and it is not easy to know what you want now.
This is described in
man bash
:Just because others have posted more “sane” answers, here’s a somewhat silly one:
rev
reverses the characters in each line, e.g.abcd/ef/g
becomesg/fe/dcba
. Thencut
chops off the first segment. Finally it’s reversed again.Another way is to use
grep
to only display the last slash per line and whatever follows it:Explanation:
-o
tellsgrep
to only show the matching part of the line instead of the whole line.The pattern
/[^/]*$
matches a literal slash/
followed by any character except for a slash[^/]
any number of times*
until the end of the line$
.Classic solution with
awk
, that treats/
as field separator for both input and output and sets the last field to empty string ( which really is "dereferencing" of the number of fieldsNF
variable ):Shorter, as fedorqui pointed out in the comments:
Variation on that would be to put path into
awk
's execution environment, which will save up on plumbing but makesawk
portion more verbose:Adding to egmont's answer because the question has been edited...
Use
--complement
if you want to remove the first field with-f1
:Also, the question isn't quite clear about what should happen with inputs not containing any slashes:
or: