1

I am trying to get a string after the last "/" character. The thing is, the number of "/" can differ. Examples:

Desktop/Picures/test.txt -> test.txt
Templates/DIR1/DIR2/DIR2/test2 -> test2
d1/d2/d3/d4/d5/d6 -> d6

...And so on, you get the idea. How can I achieve this? (btw, I need to set the result to a variable too.)

nana
  • 51
  • 6
  • 2
    `basename` should be all you need. e.g. `basename Templates/DIR1/DIR2/DIR2/test2` returns `test2` – Michael Berkowski Jul 07 '21 at 16:34
  • @MichaelBerkowski not quite.. Unless I'm doing someting wrong? I tried doing it like this - new_variable=$basename "$variable" and then I echoed it like this - echo "this is" $new_variable, but all I get is "this is" and nothing after that. (variable contains the string I want to edit) – nana Jul 07 '21 at 16:46
  • 2
    @nana The syntax for that would be `new_variable=$(basename "$variable")`. See [How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash) – that other guy Jul 07 '21 at 16:48
  • @thatotherguy oh okay thanks! – nana Jul 07 '21 at 16:49

1 Answers1

3

Use parameter expansion.

for path in Desktop/Picures/test.txt \
            Templates/DIR1/DIR2/DIR2/test2 \
            d1/d2/d3/d4/d5/d6 ; do
    echo "${path##*/}"
done

##*/ removes the longest matching pattern from the left. The pattern is */, i.e. it will remove everything up to the last slash.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • Note that this is slightly different from `basename "$path"` -- if the variable *ends with* "/", this'll give the empty string, while `basename` will return the last non-empty path element (e.g. `basename /path/to/dir/` will print "dir"). – Gordon Davisson Jul 07 '21 at 19:07