0

I need to get specific part of output from a bash script. I have a bash script which already shows the location of json file but I also need username of owner of json file.

I have tried cat userswithjson.txt | grep -o '/home/*' but it didn't work.

files=$(find /home -name file.json -print)
echo "$files" >> userswithjson.txt
cat userswithjson | grep -o '/home/*'

Expected output: user Actual output: /home/user/file.json

Content of userswithjson.txt: /home/user/file.json

fooo
  • 9
  • 2

2 Answers2

0

files could be under /home/some-user and belong to another-user. So if you want to get the name of the file owner, you could:

stat -c '%U' /path/to/your/file

which I got here

You could then simplify your script like this:

for file in $(find /home -name file.json -print)
do
    owner=$(stat -c '%U' $file)
    echo "$owner : $file"
done
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
  • It gives output root for /home/user/file.json I need output which username have file in their ~/ – fooo Aug 14 '19 at 12:21
  • which proves what I say: it is not because a file is under /home/user that it really belongs to that user. This shows that the user **root** has created the file under /home/user... it also depends on what you want to obtain with your script: the real file owner or not? – Chris Maes Aug 14 '19 at 12:22
  • Not real owner, I just need file is located at home directory of which user. – fooo Aug 14 '19 at 12:25
  • 1
    Yes, you are right. Thanks a lot for your help! And I gave a upvote but I have less than 15 reputation so it's not casted. – fooo Aug 14 '19 at 12:28
0

You can simply use awk to quickly parse your userswithjson file and output the userid portion of the file path. Here's some code that will achieve that for you:

awk -F/ '{print $3}' userswithjson 

The -F/ sets the IFS (input field separator) for awk. Awk breaks each input line into fields based on the IFS. The fields are given numeric names (like $3).

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Mark
  • 4,249
  • 1
  • 18
  • 27