"Cutting" id output

Don't bother trying to parse it. POSIX requires that id support various options to do this automatically:

printf "Login: %s\nId: %s\nGroup: %s\n" "$(id -un)" "$(id -u)" "$(id -gn)"

In addition to being more work, parsing is complicated by the fact that id with no options is permitted to produce locale-dependent output:

The following formats shall be used when the LC_MESSAGES locale category specifies the POSIX locale. In other locales, the strings uid, gid, euid, egid, and groups may be replaced with more appropriate strings corresponding to the locale.

While most reasonable parsing tools can cope with this, anything that isn't Unicode-aware may have problems.


Using multiple character field separator in awk

$ echo 'uid=12345(mylogin) gid=100(users)' | awk -F'[=()]' '{print "Login: " $3 "\nId: " $2 "\nGroup: " $6}'
Login: mylogin
Id: 12345
Group: users
  • -F'[=()]' set = or ( or ) as field separators
  • $3 will be third field, after first = and the first ( terminated by ). So it gets the value mylogin
  • Similarly for other fields and print as required

One way can be:

# 0 |  1  |   2   |  3 | 4 |  5  |
#uid=12345(mylogin) gid=100(users)
IFS='(=)' read -a A <<<"$(id)"
printf '%s: %s\n' Login "${A[2]}" Id "${A[1]}" Group "${A[5]}"
# remember array A indexing begins at 0.

Tags:

Awk

Cut