0

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 /.

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice! However, is there no other way to ensure that if the input is like /home or /Anotherfolder without a user name defined, it will default to root? (input 3) I can just let the user know to end the string with '/' if that's all I can do EDIT: silly me, you just force a /root behind to simulate a root path. Wonderful!
1

You can trry this:

owner=$(echo $path | tr '/' ' ' | awk '{print $2}')
if [ "$owner" == "" ]
    then echo root
else
    echo $owner
fi

Hope this helps. But I would recommend to use ls -l command and extract owner from there.

Comments

0

I would recommend to use ls command to get path either owner, then parse it by awk.

ls -lp /home | grep "/$" | tr -d '/' | awk '{print "Input:", $9, "\nOwner:", $3, "\n"}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.