Search code examples
linuxindexofsubstr

Linux: finding the position of the last '/' in a string only


I have this string:

/sandbox/US_MARKETING/COMMON_DATA/BAU/FILES/2020/08/dnb_mi_081420.gz

Without knowing how many '/' there are in it, I want to be able to read just the file into a variable.

I want to be able to do a search where I start at the last '/' in the line and find the filename 'dnb_mi_081420.gz'.

I want to basically say "Find the last '/' in the string and then read the substring that comes after it to the end and store it.

So I know it's going to look like this:

filename=substr(<position of the last'/'>,<position of first character in last string>)

So how to find the index position of the last '/' is I guess what I'm looking for.

Does anyone know what that is?

Also I tried using basename and unfortunately I'm doing this through 'hdfs dfs' to get to a hadoop shell. So some of the non-standard Linux commands like basename aren't in that vocabulary. I'm basically going to have to store that whole string in a variable and do operations on that variable value.


Solution

  • In bash, parameter expansion can be used:

    ${parameter##word}

    The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning 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

    Example:

    $ s="/sandbox/US_MARKETING/COMMON_DATA/BAU/FILES/2020/08/dnb_mi_081420.gz" && echo ${s##*/}
    dnb_mi_081420.gz
    $