LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   s there a way to determine the owner of a file by using a script? (https://www.linuxquestions.org/questions/programming-9/s-there-a-way-to-determine-the-owner-of-a-file-by-using-a-script-408235/)

DHoody 01-26-2006 10:59 AM

s there a way to determine the owner of a file by using a script?
 
Example:

-rw-rw---- 1 xxx01 CGroup 20992 Nov 3 15:42 File001.doc
-rw-rw-r-- 1 xxx02 CGroup 19456 Aug 19 2002 File002.doc
-rw-rw---- 1 xxx03 CGroup 18432 Jul 13 2005 File003.xls
12345678901234567

I will know the file name, such as File002.doc. What I need to get is the owner xxx02. I could use cut to (ls -l testp | cut -b 17-21) in this example, but that would assume a 5 character owner name. Maybe there is another command that will get the file's owner? Any other ideas on determining the owner of a file by using a script?

Hko 01-26-2006 11:40 AM

Quote:

Originally Posted by DHoody
I will know the file name, such as File002.doc. What I need to get is the owner xxx02. I could use cut to (ls -l testp | cut -b 17-21) in this example, but that would assume a 5 character owner name.

This could be solved by cutting by field number (option: -f4). For this, you need to specify spaces as seperator (option: -d' '). Example:
Code:

ls -l File002.doc | cut -d' ' -f4
But because "cut" sees each space as a seperator, it may not be very reliable. A solution using "sed", "awk", "python", "perl" would better, but slower.

Another way by setting shell arguments:
Code:

set -- $(ls -l File002.doc)
# Now $1, $2, $3,.. are set to the different fields in
# the output of "ls":
echo "Owner: $3"
echo "Group: $4"
echo "Size:  $5"

But probably the most reliable, shortest and fastest way is to use "stat" instead of "ls":
Code:

stat -c%U File002.doc

pljvaldez 01-26-2006 11:41 AM

Try using

Code:

ls -l filename | awk '{ print $3 }'

DHoody 01-26-2006 12:09 PM

Wow...Not just one but, 3 great ways to get the job done. Thanks Hko and pljvaldez. stat will work best for my current script, but I see uses for the other options too. Excellent.

bigearsbilly 01-27-2006 10:01 AM

make that four ;)

Code:

billym.>set `ls -l ~/.profile`
billym.>echo $3,$4
billym,prima



All times are GMT -5. The time now is 02:38 PM.