我如何按字母顺序列出所有用户,并查看前10个用户的用户ID信息(第5列)?对于问题的第一部分,我知道可以使用类似以下的命令:
cat /etc/passwd | cut -d ':' -f1 | sort
但是对于第二部分,我应该使用“for”或“if”或类似的东西吗?使用 grep
命令删除标题,然后使用 cut
命令:
cat /etc/passwd | grep -v '^#' | cut -d: -f1,5
使用GNU awk:
awk -F: '{
users[cnt++]=$1 # Set up an array with the users (first : separated field) as the value
}
END {
PROCINFO["sorted_in"]="@val_str_asc"; Set the array sort order to value ascending
for ( i in users ) { # Loop through each entry in the array
if ( cnt1 <= 4) { # Only print the first 5
print users[i];
cnt1++ # Use to track number of prints
}
}
}' /etc/passwd
一句话简介
awk -F: '{ users[cnt++]=$1 } END { PROCINFO["sorted_in"]="@val_str_asc";for ( i in users ) { if ( cnt1 <= 4) { print users[i];cnt1++ } } }' /etc/passwd