BASH Shellscript get username from folder path

Kei :

Given a folder path that has /home, I would like to scrape the username from the folder path. (A little home work, trying to compare folder username to actual owner of the folder, which can be determined with a quick stat -c '%U' path

Input1: /home/user1/Music
Output1: user1

Input2: /home/user2
Output2: user2

Input3: /home
Output3: root

I have managed to come up with something that is able to cater to Input1, but I am unable to come up with something to cater to the other two inputs.

owner=$(path | grep -oP '(?<=home/).*(?=/)') This will scrape anything that is between home/ and the next /.

Teshan Shanuka J :

A bit of a hack

owner=$(cut -d/ -f3 <<< "$path/root")

A more complete answer to deal with input 3 in the form Input3: /home/ or paths like /home//user3

owner=$(tr -s '/' <<< "$path/root" | cut -d/ -f3)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33062&siteId=1