I want to format output of a user account from /etc/passwd
to display only the name, role, and directory path, all separated by commas. I know this should be easy, but for the life of me I cannot figure out how to display between certain colons. (Note this should work with any username, not just the ex)
Ex of grep joe /etc/passwd
:
joe:x:1001:1001:System Admin:/home/joe:/bin/bash
Desired Output :
joe, System Admin, /home/joe
Thank you!
awk 'BEGIN{ FS=":"; OFS=", " } $1=="joe" { print $1,$5,$6; exit }' /etc/passwd
(但是下次您应该付出更多的努力-您的问题非常令人讨厌:)
使用cut
将逗号用作--output-delimiter
:
cut -d: -f1,5,6 --output-delimiter=, /etc/passwd
Try:
grep joe /etc/passwd | cut -d: -f1,5,6
If you really need "," as a delimiter:
grep "^joe:" /etc/passwd | cut -d: -f1,5,6 | tr : ,
The "^" ensures only matches to "joe" at the beginning of the line are intercepted (Thanks PSkocik for the reminder). grep
by defaults accepts a regex
.
Translation in bash, but two lines:
x=`grep joe /etc/passwd | cut -d: -f1,5,6`
echo ${x/:/,}
If you want to do it purely in shell (POSIX sh is enough, Bash not needed), then read
is your friend:
while IFS=: read user pw uid gid gecos home shell ; do
if [ "$user" = "joe" ] ; then
echo "$user, $gecos, $home"
fi
done < /etc/passwd
Adding to the variations, in bash itself, you can pipe the output of grep
directly to a brace enclosed read
and separate the fields using IFS
as required. Using short names for the fields, you could do:
grep '^joe:' /etc/passwd |
{ IFS=: read -r u x uid gid n h s; echo "$u, $n, $h"; }
Which would give the output you seek (if /etc/passwd
contained the entry)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.