0

I need a sed solution for the work I am doing. I need to extract the name from /etc/passwd file based on the AIX user id (username). So far I have this and it isn't working. Any working solution would be appreciated.

sed "/^Ravi02/s/\(^.\{21\}\).\([a-zA-Z]\{50\}\)/\1/p" /export/home/Ravi02/passwd 

Here are some example entries from the passwd file:

Jose01:!:49030:49082:Freeman, Joseph III:/export/home/p1jxf01:/bin/ksh Ravi02:!:37242:1580:Dronavalli, Ravi:/export/home/j1rxd02:/bin/ksh Beny01:!:49335:49040:Young, Ben:/export/home/p1bmy01:/bin/ksh 

Based on the id I need to extract the name.  If the id is "Jose01" I should get "Freeman, Joseph III" or if it the id is "Ravi02" then I should get "Dronavalli, Ravi".

7
  • 2
    Does the solution have to be sed? Would awk or other tools also be acceptable? Commented Sep 19, 2016 at 18:17
  • 1
    Or on AIX have you considered using lsuser instead? Commented Sep 19, 2016 at 18:18
  • Here is some example entries from the passwd file. Commented Sep 19, 2016 at 18:32
  • Jose01:!:49030:49082:Freeman, Joseph III:/export/home/p1jxf01:/bin/ksh Ravi02:!:37242:1580:Dronavalli, Ravi:/export/home/j1rxd02:/bin/ksh Beny01:!:49335:49040:Young, Ben:/export/home/p1bmy01:/bin/ksh Commented Sep 19, 2016 at 18:32
  • 3
    I think you're better off with grep "^Ravi02:" /etc/passwd | cut -d: -f5. Commented Sep 19, 2016 at 18:40

2 Answers 2

1

The passwd file is a : delimited file. So the first field is always the username, and so on.

(Side note: man 5 passwd describes the fields).

In this case, given a username you want the GECOS field.

This could be done with sed, but other tools may be better. awk makes it simple:

awk -F: '$1 == "Ravi02" { print $5 }' /etc/passwd 
0

The standard sed solution would be

sed -n '/^Ravi02:/s/^[^:]*:[^:]*:[^:]*:[^:]*:\([^:]*\):[^:]*:[^:]*$/\1/p' 

which can be simplified slightly to

sed -n 's/^Ravi02:[^:]*:[^:]*:[^:]*:\([^:]*\):[^:]*:[^:]*$/\1/p' 

The key is that you need to be looking at (counting) colons (:) and characters other than colon, rather than counting characters (.\{21\}) and letters ([a-zA-Z]\{50\}) — especially since you want to be able to match characters like comma (,) and space in the full name field.

On my system, the following variations also work:

  • sed -n '/^Ravi02:/s/^\([^:]*:\)\{4\}\([^:]*\)\(:[^:]*\)\{2\}$/\2/p'
  • sed -n 's/^Ravi02:\([^:]*:\)\{3\}\([^:]*\)\(:[^:]*\)\{2\}$/\2/p'
  • sed -nE '/^Ravi02:/s/^([^:]*:){4}([^:]*)(:[^:]*){2}$/\2/p'
  • sed -nE 's/^Ravi02:([^:]*:){3}([^:]*)(:[^:]*){2}$/\2/p'

but I’m not sure whether they will all work on all systems (e.g., AIX).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.