Link to home
Start Free TrialLog in
Avatar of akohan
akohan

asked on

extracting a path from a string


Hello,

I want to extract a portion of a string. The string is a path which beloings to an entry in /etc/passwd file

Let's assume the line is:

user_A:x:100:0:ABC User Account:/Dir1/Dir2/Dir3:/bin/sh

I did:

      cat /etc/passed | grep user_A  | awk '{ print $3}'  

this prints:  Account:/Dir1/Dir2/Dir3:/bin/sh

but I need to extract "/Dir1/Dir2/Dir3/" only, neither before it nor after it.

Any suggestions?
Thanks
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
perl -e 'while(split(":",<>)) { print $_[5];}'
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
perl -ne 'print ((split":")[5],"\n")'
perl -F: -lane 'print $F[5]'
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
cat /etc/passwd | grep 'user_A' | cut -s -d':' -f6

the earlier would give all the home directories of all users.  this one gives only specific user. can be put in a script and a parameter can also be given as $1 for any specific user
perl -F: -lane 'print $F[5] if /^user_A:/' /etc/passwd
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tintin
Tintin

If you are using grep/cut, the more usual way is

grep 'user_A' /etc/passwd|cut -d: -f6

But note that will match *any field in /etc/passwd that *contain* user_A, eg:

Myuser_ABC

The awk solution is the easiest and most sensible.