How to extract a segment of a path

how to combine rev and cut to extract a segment of a path

When we write a bash script, we may need to manipulate the paths of files and directories. For example, we are iterating over a set of directories and we want to take a different action based on their name, or the name of the parent. What we can do in this case is to use the cut command. Unfortunately, cut starts cutting from left to write, given a separator (which is “/” for paths and URLs). If we do not know how many segments there are in a path and we need to access the last or the last but one segment, we can use rev before and after cut to achieve our goal. Let’s see an example. Let’s say we have paths like:
/mnt/disks/data/work/2018
/mnt/disks/data/work/2020
/mnt/disks/data/work/2021
...
and we want to extract the last segment (2018, 2020, 2021). Let’s also assume that we do not know the number of segments of the path and that we want to write a generic script that works for different paths. If the path is available in a variable $PATH, we can write the following command:
EXTRACTED_SEGMENT=`echo $PATH | rev | cut -d "/" -f1 | rev`
Let me explain the command. The back quotes `` are used to assign the results of a command to variables, in this case EXTRACTED_SEGMENT. The command is a sequence of commands. We start accessing the path from the variable PATH, we reverse it to allow cut to extract the first segment (segments are separated by the character "/), and then we reverse again to restore the way we display the segment.
This command can be useful when used into a loop. For example, let’s iterate over all the directories in the current directory, extracting the last fragment of their path:
					
for dir in ./* ; do
    if [ -d "$dir" ]; then
        EXTRACTED_SEGMENT=`echo $dir | rev | cut -d "/" -f1 | rev`
        # use the segment
        echo $EXTRACTED_SEGMENT
    fi	    
done
				
More information about the for command is available here.
If we want to extract the last but one fragment, we just use the option -f2:
EXTRACTED_SEGMENT=`echo $PATH | rev | cut -d "/" -f2 | rev`
Finally, note that this technique is useful in a lot of scenarios, not only for paths. It is useful for any string given a specific separator.