[CentOS] OT: bash script for passwd and shadow manipulation

Thu Nov 27 19:23:06 UTC 2008
Robert <kerplop at sbcglobal.net>


Erick Perez wrote:
> Hi,
> i need to extract some information from the /etc/passwd file to be
> used as a command input in a mail software. My /etc/passwd looks like:
> k.thomas:x:1918:100:Kimaura Thomas:/home/users/k.thomas:/bin/usersh
> My main issue here is that the fifth field contains spaces and spanish
> chars with accent. I currently do not posess the skill to understand
> how to use cut to extract all the field.
> So far, cut returns the name up to the space, so in this case it will
> return Kimaura and not Kimaura Thomas.
> Can you please point me to internet examples of tools (sed, awk, grep
> or cut) that will help me accomplish this, or maybe provide the code?
>
> And here is the code (not the best...im still learninng..)
> #!/bin/bash
> # Passwd to Zimbra import
> # This script modifies the displayName field in the Zimbra mailserver
> # This script will parse /etc/passwd and extracts field 1 and field 5
> # field 1 is the username.
> # field 5 is the name in long format of the username
> #
> # domain="oj.gob.pa"
> # file="zimbranames.file"
> # x=0
> # echo ''>$file
> #
> # for linia in `cat /etc/passwd`
> # do
> #    user=`echo $linia|cut -f1 -d":"`
> #    nombre=`echo $linia|cut -f5 -d":"`
> #    echo "zmprov ma $user@$domain displayName $nombre">>$file
> #    x=$[x+1]
> # done
> # echo "$x accounts exported to \"$PWD/$file\""
> # sleep 5
>
> Thanks in advance.
>   
You should be able to do this easily with awk.  Look at the -F option 
for defining fields.  The follow command line will pluck field 1 and 
field 5 from your example.
$ echo "k.thomas:x:1918:100:Kimaura 
Thomas:/home/users/k.thomas:/bin/usersh" | awk -F : '{ print $1", "$5 }'
Or, in your script
.
.
.
user=echo $linea | awk -F :  '{ print $1 }'
nombre=echo $linea | awk -F :  '{ print $5 }'
.
.
.
That's about as inelegant as it comes but it should be easy to 
understand.  There is a fantastic (g)awk manual at 
http://www.gnu.org/software/gawk/manual/ presented in a number of formats.