29

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
5
  • Good question, I just realised that we didn't understand the question the same way
    – Félicien
    Feb 27, 2018 at 15:35
  • 4
    The commands basename and dirname do this already. Feb 28, 2018 at 0:49
  • I don't think edit #5 to the question was correct. Using the word "cut" might be ambiguous; if you cut something, do you throw away that part, or do you keep only that? However, the previous wording "and to omit what is before the /" was unambiguous. This was changed to its opposite.
    – egmont
    Mar 1, 2018 at 0:02
  • @egmont the word "cut" itself was carried over from the original: "I need to cut only the charachters after the last /" became "How do I cut all characters after the last '/'?" which is a change of phrasing that reasonably keeps the meaning, IMO. If anything, I felt the "omit what is ..." part ambiguous: the examples seem to keep what is before the /. The example, makes it clear, anyway.
    – muru
    Mar 1, 2018 at 4:30
  • @muru I'm talking about the edit that added the examples, not your edit.
    – egmont
    Mar 1, 2018 at 7:32

7 Answers 7

34

If you want to get the "cutted part"

yyy
yyyyy

You can use

sed 's|.*/||' 

eg.

echo "xxx/xxxx/xxxxx/yyy" | sed 's|.*/||'
echo "xxxx/x/xx/xx/xxxx/x/yyyyy" | sed 's|.*\/||'

output

yyy
yyyyy

(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 :

xxx/xxxx/xxxxx
xxxx/x/xx/xx/xxxx/x

You can use

sed 's|\(.*\)/.*|\1|'

eg.

echo "xxx/xxxx/xxxxx/yyy" | sed 's|\(.*\)/.*|\1|'
echo "xxxx/x/xx/xx/xxxx/x/yyyyy" | sed 's|\(.*\)/.*|\1|'

output

xxx/xxxx/xxxxx
xxxx/x/xx/xx/xxxx/x
2
  • 6
    Hi, in this case you can change the delimiter, for example # instead of /. Also you can use the option -r if you don't want to escape ` \ ` each special character: sed -r 's#(^.*)/.*$#\1#'.
    – pa4080
    Feb 27, 2018 at 15:49
  • 1
    I have submitted a proposed edit to use | instead of /. If you don't like it, I suggest you "reject and edit" it, and change "begginning" to "beginning". (Reject+Edit, because that way it won't get approved by robo-approvers. Alternatively, just roll the change back if it has got approved and you didn't like it.) Mar 1, 2018 at 6:33
25

Parameter expansion in bash

You can use parameter expansion in bash, in this case

  • ${parameter%word} where word is /*
  • ${parameter##word} where word is */

Examples:

Remove the last part

$ asdf="xxx/xxxx/xxxxx/yyy"
$ echo ${asdf%/*}
xxx/xxxx/xxxxx

This is described in man bash:

${parameter%word}
${parameter%%word}
      Remove matching suffix pattern.  The word is expanded to produce
      a pattern just as in pathname expansion.  If the pattern matches
      a  trailing portion of the expanded value of parameter, then the
      result of the expansion is the expanded value of parameter  with
      the  shortest  matching  pattern (the ``%'' case) or the longest
      matching pattern (the ``%%'' case) deleted.  If parameter  is  @
      or  *,  the  pattern  removal operation is applied to each posi‐
      tional parameter in turn, and the  expansion  is  the  resultant
      list.   If  parameter is an array variable subscripted with @ or
      *, the pattern removal operation is applied to  each  member  of
      the array in turn, and the expansion is the resultant list.

Remove all except the last part

$ asdf="xxx/xxxx/xxxxx/yyy"
$ echo ${asdf##*/}
yyy

You can add a slash like so

$ echo /${asdf##*/}
/yyy

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:

${parameter#word}
${parameter##word}
      Remove matching prefix pattern.  The word is expanded to produce
      a pattern just as in pathname expansion.  If the pattern matches
      the  beginning of the value of parameter, then the result of the
      expansion is the expanded value of parameter with  the  shortest
      matching  pattern  (the ``#'' case) or the longest matching pat‐
      tern (the ``##'' case) deleted.  If parameter is  @  or  *,  the
      pattern  removal operation is applied to each positional parame‐
      ter in turn, and the expansion is the resultant list.  If param‐
      eter  is  an array variable subscripted with @ or *, the pattern
      removal operation is applied to each  member  of  the  array  in
      turn, and the expansion is the resultant list.
0
23

If you're cutting off the ends of the strings,dirname might fit the bill:

$ dirname xxxx/x/xx/xx/xxxx/x/yyyyy
xxxx/x/xx/xx/xxxx/x
$ _

If you're trying to isolate the last part of the string, use echo /$(basename "$str").

$ str=xxxx/x/xx/xx/xxxx/x/yyyyy
$ echo /$(basename "$str")
/yyyyy
$ _
3
  • 3
    Honestly, why anyone would either suggest or accept an answer involving sed (or awk, or any other similar method) instead of just using the utilities installed with the OS is beyond me.
    – Auspex
    Feb 28, 2018 at 11:48
  • @Auspex I'd guess it's simply because dirname and basename are not widely known, but sed and awk are. Feb 28, 2018 at 13:08
  • @Auspex: Because dirname and basename don't operate on stdin, therefore cat text | basename won't work. So a proper solution to OP's question using dirname and basename would involve xargs etc.
    – Pod
    Jan 6, 2020 at 9:48
14

Just because others have posted more “sane” answers, here’s a somewhat silly one:

rev | cut -d/ -f2- | rev

rev reverses the characters in each line, e.g. abcd/ef/g becomes g/fe/dcba. Then cut chops off the first segment. Finally it’s reversed again.

3
  • 2
    Despite the non-sanity of this answer, especially because of the shell plumbing, I like this answer :) Keep on rocking, +1 Feb 28, 2018 at 2:32
  • Agreed - not sane, but badass! Feb 28, 2018 at 12:12
  • To be honest, I find this a very elegant solution. Dec 15, 2021 at 15:25
11

Another way is to use grep to only display the last slash per line and whatever follows it:

$ grep -o '/[^/]*$' example.txt
/yyy
/yyyyy

Explanation:

-o tells grep 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 $.

4

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 fields NF variable ):

$ echo "xxx/xxxx/xxxxx/yyy"|awk  'BEGIN{OFS=FS="/"};{$NF="";print $0}'
xxx/xxxx/xxxxx/

Shorter, as fedorqui pointed out in the comments:

$ echo "xxx/xxxx/xxxxx/yyy"|awk  'BEGIN{OFS=FS="/"};NF--'
xxx/xxxx/xxxxx/

Variation on that would be to put path into awk's execution environment, which will save up on plumbing but makes awk portion more verbose:

mypath="xxx/xxxx/xxxxx/yyy" awk  'BEGIN{OFS=FS="/"; sub(/\/([^\/]*)$/,"",ENVIRON["mypath"]);print(ENVIRON["mypath"]) };'
1
  • 1
    Too verbose, why not just NF--? This way you avoud the print bla bla.
    – fedorqui
    Feb 28, 2018 at 9:35
4

Adding to egmont's answer because the question has been edited...

Use --complement if you want to remove the first field with -f1:

$ echo "xxxx/x/xx/xx/xxxx/x/yyyyy"|rev|cut -d/ -f1 --complement|rev
xxxx/x/xx/xx/xxxx/x

$ echo "xxxx/x/xx/xx/xxxx/x/yyyyy"|rev|cut -d/ -f1|rev
yyyyy

Also, the question isn't quite clear about what should happen with inputs not containing any slashes:

xxxx => xxxx

or:

xxxx => *nothing*
2
  • +1 - I had not noticed the --complement option before and the man page is circular. Complement means complement. I found a nice cut tutorial which covers it at yourownlinux.com/2015/05/… It's like -v in grep. Give me everything except what was matched.
    – Joe
    Feb 28, 2018 at 23:59
  • 2
    -f2- is a simpler form for -f1 --complement.
    – egmont
    Mar 1, 2018 at 0:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .